我想提取两个日期并在几秒钟内显示结果。我这样做:
dftask['TimeWindowDuration'] = dftask['LatestEnd'] - dftask['EarliestStart']
LatestEnd和EarliestStart都是:datetime64[ns]
相应的输出数据帧:
LatestEnd EarliestStart TimeWindowDuration
27-7-2015 22:57 27-7-2015 22:14 0 days 00:43:00.000000000
28-7-2015 6:20 28-7-2015 1:50 0 days 04:30:00.000000000
28-7-2015 6:45 27-7-2015 20:32 0 days 10:13:00.000000000
28-7-2015 7:00 27-7-2015 21:47 0 days 09:13:00.000000000
28-7-2015 6:15 28-7-2015 1:45 0 days 04:30:00.000000000
如何指定TimeWindowDuration是以秒为单位? unit='s'
感谢您的帮助!
答案 0 :(得分:2)
尝试将timedelta.total_seconds()
用作:
dftask['TimeWindowDuration'].total_seconds()
示例:
d1 = datetime(2015, 10, 1, 10, 56, 21)
d2 = datetime(2015, 10, 1, 10, 58, 21)
d3 = d2-d1
In [21]: d3.total_seconds()
Out[21]: 120.0
编辑:
让:
In [5]: import pandas as pd
In [6]: a = pd.to_timedelta('0 days 00:43:00.000000000',unit='s')
In [7]: a
Out[7]: Timedelta('0 days 00:43:00')
In [8]: a.total_seconds()
Out[8]: 2580.0
希望有所帮助。
编辑2:
在您的数据框中:
dftask['TimeWindowDuration'] = (dftask['LatestEnd'] - dftask['EarliestStart']).dt.seconds
请记住阅读数据框或使用parse_dates=['LatestEnd','EarliestStart']
将列解析为日期。