减去两个DateTime对象-Python [英] Subtract Two DateTime objects - Python
问题描述
我有两个这样的日期时间对象
I have two date time objects like this
a = first date time object
b = second date time object
然后
c = a - b
现在,我想比较c并检查时差是否大于3小时,所以我有一个名为 three_hours
Now I want to compare c and check if the difference was greater than 3 hours, so I have a time object called three_hours
three_hours = datetime.time(3,0)
if c >= three_hours:
#do stuff
但是我收到一条错误消息,说无法将datetime.teimdelta与datetime.time进行比较
but I get an error saying cannot compare datetime.teimdelta to datetime.time
我的问题有所不同,因为我也想比较减去的时间,而不仅仅是得到差异!
My question is different as I also want to then compare the subtracted time, not just get the difference!!
如何将它们转换为正确的格式,以便检查是否已过去3个小时?
How can I convert them to the correct formats so I can check if 3 hours has passed?
感谢您的帮助
推荐答案
在python中减去两个datetime对象时,您会得到一个
When you subtract two datetime objects in python, you get a datetime.timedelta
object. You can then get the total_seconds()
for that timedelta object and check if that is greater than 3*3600
, which is the number of seconds for 3 hours. Example -
>>> a = datetime.datetime.now()
>>> b = datetime.datetime(2015,8,25,0,0,0,0)
>>> c = a - b
>>> c.total_seconds()
87062.729491
>>> c.total_seconds() > 3*3600
True
这篇关于减去两个DateTime对象-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!