首页 > 解决方案 > 获取 datetime 和恒定时间变量 pandas 之间的时间差

问题描述

我有一个 DateTime 列“已结束”,如果时间大于 19:00:00 否则要创建一个新列 0。新列应包含“已结束”和 19:00:00 之间的差异(以小时为单位)。 .

Ended                   New_Ended
2020-10-31 21:06:30     2.1
2020-10-31 20:29:18     1.5
2020-10-01 19:24:42     0.4
2020-10-03 16:24:42     0.0


datetime64[ns]

同样,如果“开始”在 08:30 之前,则以小时为单位获得“开始”和 8:30 之间的时间差

Open                   New_Open
2020-10-22 7:56:00      0.56

标签: pandasnumpydataframedatetime

解决方案


我们试试看

# add 19:00:00 to the starts of the days
end_thresh = df['Ended'].dt.floor('D') + pd.Timedelta('19H')

df['New Ended'] = (df['Ended'].sub(end_thresh)   # subtract the threshold
                     .div(pd.Timedelta('1H'))    # divide by 1H
                     .clip(lower=0)              # replace negatives with 0
                  )

输出:

                Ended  New_Ended
0 2020-10-31 21:06:30   2.108333
1 2020-10-31 20:29:18   1.488333
2 2020-10-01 19:24:42   0.411667
3 2020-10-03 16:24:42   0.000000

相同的逻辑Open除了你将交换 thresh 和减法列。


推荐阅读