gpt4 book ai didi

python-3.x - 在 Pandas 中以分钟计算2个日期的差异

转载 作者:行者123 更新时间:2023-12-02 00:59:40 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Calculate Time Difference Between Two Pandas Columns in Hours and Minutes

(3 个回答)


去年关闭。




我在数据框中有 2 列。我想在几分钟内计算 2 列的差异并将结果写入新列

Input

Planned Pickup date/time Actual Pickup date/time
07/05/2018 09:28:00 07/05/2018 09:33:15
14/05/2018 17:00:00 15/05/2018 08:44:08
15/05/2018 17:00:00 15/05/2018 10:52:50
15/05/2018 17:00:00 15/05/2018 15:03:34
15/05/2018 17:00:00 15/05/2018 15:03:34
16/05/2018 17:00:00 16/05/2018 16:00:38

我想在几分钟内计算实际和计划取货的差异,并将结果写入数据帧中名为 data['time difference'] 的新列中

Expected Output
Planned Pickup date/time    Actual Pickup date/time      Time Difference
07/05/2018 09:28:00 07/05/2018 09:33:15 5
14/05/2018 17:00:00 15/05/2018 08:44:08 944
15/05/2018 17:00:00 15/05/2018 10:52:50 -368
15/05/2018 17:00:00 15/05/2018 15:03:34 -117
15/05/2018 17:00:00 15/05/2018 15:03:34 -117
16/05/2018 17:00:00 16/05/2018 16:00:38 -60

这如何在 Pandas 中完成

最佳答案

用:

data['time difference'] = ((pd.to_datetime(data['Actual Pickup date/time']) - 
pd.to_datetime(data['Planned Pickup date/time']))
.dt.total_seconds() / 60)
print (data)

Planned Pickup date/time Actual Pickup date/time time difference
0 07/05/2018 09:28:00 07/05/2018 09:33:15 5.250000
1 14/05/2018 17:00:00 15/05/2018 08:44:08 944.133333
2 15/05/2018 17:00:00 15/05/2018 10:52:50 -367.166667
3 15/05/2018 17:00:00 15/05/2018 15:03:34 -116.433333
4 15/05/2018 17:00:00 15/05/2018 15:03:34 -116.433333
5 16/05/2018 17:00:00 16/05/2018 16:00:38 -59.366667

或者如果需要 floor值(value)观:
data['time difference'] = ((pd.to_datetime(data['Actual Pickup date/time']) - 
pd.to_datetime(data['Planned Pickup date/time']))
.astype('<m8[m]').astype(int))
print (data)


Planned Pickup date/time Actual Pickup date/time time difference
0 07/05/2018 09:28:00 07/05/2018 09:33:15 5
1 14/05/2018 17:00:00 15/05/2018 08:44:08 944
2 15/05/2018 17:00:00 15/05/2018 10:52:50 -368
3 15/05/2018 17:00:00 15/05/2018 15:03:34 -117
4 15/05/2018 17:00:00 15/05/2018 15:03:34 -117
5 16/05/2018 17:00:00 16/05/2018 16:00:38 -60

关于python-3.x - 在 Pandas 中以分钟计算2个日期的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51491724/

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