import pandas as pd
from datetime import *
# 建立计算时间差的数据表(Dataframe)
li = [["2021-05-6 10:00:00", "2022-05-10 08:30:00"],
["2022-05-7 08:30:00", "2022-05-10 12:30:00"],
["2022-05-9 12:00:00", "2022-05-10 14:30:00"]]
df = pd.DataFrame(li, columns=["date1", "date2"])
# 将数据数据转换为“datetime.datetime类型”
df.date1 = df.date1.map(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S"))
df.date2 = df.date2.map(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S"))
df
# 计算时间差
df["duration"] = df.date2 - df.date1
# 对计算差值进行天数(days)和秒数(seconds)的提取,并将秒数转换为小时数
df["day"] = df.duration.map(lambda x: x.days)
df["hour"] = df.duration.map(lambda x: x.seconds/3600)
df
参考链接:https://blog.csdn.net/weixin_45914452/article/details/124745960