如何在python中只减去datetime对象的时间

时间:2016-05-24 07:06:13

标签: python datetime

我想减去2列之间的时间:我一直在使用它:

row['window'] = datetime.datetime.strptime(row['Time'], '%H:%M:%S.%f') - datetime.datetime.strptime(row['announcement_time'], '%H:%M:%S')

这样可以产生如下结果:

 window
-1 day, 23:29:00
-1 day, 23:29:05
-1 day, 23:29:10
-1 day, 23:29:15
-1 day, 23:29:20
-1 day, 23:29:25

但是,我只想要时差,即 - 00:00:30。我试过了:

 row['window'] = datetime.datetime.strptime(row['Time'], '%H:%M:%S.%f').time() - datetime.datetime.strptime(row['announcement_time'], '%H:%M:%S').time()

但这会产生错误:

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

我也试过.hour,.minute和.second但是效果不好。 请有人帮忙。谢谢

2 个答案:

答案 0 :(得分:0)

时间对象没有我所知道的算术。为了获得最佳实践,您应该使用(datetime.datetime object - datetime.datetime object).days

You can read more about it here

答案 1 :(得分:0)

-1 day, 23:29:25是如何打印否定timedelta的。要获得00:00:30,请使用abs()

>>> from datetime import timedelta
>>> -timedelta(seconds=30)
datetime.timedelta(-1, 86370)
>>> str(-timedelta(seconds=30))
'-1 day, 23:59:30'
>>> str(abs(-timedelta(seconds=30)))
'0:00:30'

如果timedelta()超过一天,您可以应用模运算,以获得一天内的时差:

>>> str(abs(-timedelta(days=10, seconds=30)))
'10 days, 0:00:30'
>>> str(abs(-timedelta(days=10, seconds=30)) % timedelta(days=1))
'0:00:30'

在Python 2上,% timedelta()未实现。您可以使用.total_seconds() % 3600代替,或者如果您只需要整数秒,那么只需访问.seconds属性(它总是少于一天):

>>> abs(-timedelta(days=10, seconds=30)).seconds
30