我想提取两个日期并以秒为单位显示结果。我做:

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'

谢谢您的帮助!

最佳答案

尝试将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']将列解析为日期。

关于python - 提取两个日期,以秒为单位( Pandas ),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32883104/

10-12 20:22