gpt4 book ai didi

python - 如何在 Pandas 中以分钟为单位获得时差

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:15 25 4
gpt4 key购买 nike

我在 Pandas 中有以下数据框

  code     start_time      end_time
0 13:00:09 13:30:09
1 14:23:33 15:23:23
2 11:30:00 12:30:00

start_timeend_time 是对象类型。

我想在几分钟内得到这两列的差异。我在 Pandas 中做以下事情

df['time_diff'] = pd.Timestamp(df['start_time']) - pd.Timestamp(df['end_time'])   

最佳答案

to_datetime 将列转换为日期时间或通过 to_timedelta 到 timedeltas , 减去 sub , 将输出时间增量转换为 total_seconds并划分 60:

start_time = pd.to_datetime(df['start_time'].astype(str)) 
end_time = pd.to_datetime(df['end_time'].astype(str))

#another solution
#start_time = pd.to_timedelta(df['start_time'].astype(str))
#end_time = pd.to_timedelta(df['end_time'].astype(str))

df['time_diff'] = start_time.sub(end_time).dt.total_seconds().div(60)
print (df)
code start_time end_time time_diff
0 0 13:00:09 13:30:09 -30.000000
1 1 14:23:33 15:23:23 -59.833333
2 2 11:30:00 12:30:00 -60.000000

如果交换结束时间和开始时间:

df['time_diff'] = end_time.sub(start_time).dt.total_seconds().div(60)
print (df)
code start_time end_time time_diff
0 0 13:00:09 13:30:09 30.000000
1 1 14:23:33 15:23:23 59.833333
2 2 11:30:00 12:30:00 60.000000

示例:

import datetime

df = pd.DataFrame({'code': [0, 1, 2],
'start_time': [datetime.time(13, 0, 9), datetime.time(14, 23, 33),
datetime.time(11, 30)],
'end_time': [datetime.time(13, 30, 9), datetime.time(15, 23, 23),
datetime.time(12, 30)]})

print (df)
code start_time end_time
0 0 13:00:09 13:30:09
1 1 14:23:33 15:23:23
2 2 11:30:00 12:30:00

IDE 来自评论,感谢@Anton vBR:

start_time = pd.to_timedelta(df['start_time'].astype(str)).dt.total_seconds()
end_time = pd.to_timedelta(df['end_time'].astype(str)).dt.total_seconds()

df['time_diff'] = end_time.sub(start_time).div(60)
print (df)
code start_time end_time time_diff
0 0 13:00:09 13:30:09 30.000000
1 1 14:23:33 15:23:23 59.833333
2 2 11:30:00 12:30:00 60.000000

关于python - 如何在 Pandas 中以分钟为单位获得时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52584945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com