计算熊猫中2个日期的分钟差[重复]
Posted
技术标签:
【中文标题】计算熊猫中2个日期的分钟差[重复]【英文标题】:Calculate difference of 2 dates in minutes in pandas [duplicate] 【发布时间】:2018-12-31 16:03:20 【问题描述】:我在数据框中有 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 中做到这一点
【问题讨论】:
【参考方案1】:用途:
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
值:
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
【讨论】:
以上是关于计算熊猫中2个日期的分钟差[重复]的主要内容,如果未能解决你的问题,请参考以下文章