减去两个 DateTime 对象 - Python
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32211596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subtract Two DateTime objects - Python
提问by spenf10
I have two date time objects like this
我有两个这样的日期时间对象
a = first date time object
b = second date time object
And then
进而
c = a - b
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
现在我想比较 c 并检查差异是否大于 3 小时,所以我有一个名为的时间对象 three_hours
three_hours = datetime.time(3,0)
if c >= three_hours:
#do stuff
but I get an error saying cannot compare datetime.teimdelta to datetime.time
但我收到一条错误消息,提示无法将 datetime.teimdelta 与 datetime.time 进行比较
My question is different as I also want to then compare the subtracted time, not just get the difference!!
我的问题是不同的,因为我还想比较减去的时间,而不仅仅是得到差异!!
How can I convert them to the correct formats so I can check if 3 hours has passed?
如何将它们转换为正确的格式,以便我可以检查 3 小时是否已经过去?
Thanks for the help
谢谢您的帮助
采纳答案by Anand S Kumar
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 -
当你在 python 中减去两个 datetime 对象时,你会得到一个datetime.timedelta
对象。然后,您可以获取该total_seconds()
timedelta 对象的 并检查它是否大于3*3600
,这是 3 小时的秒数。例子 -
>>> 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
回答by YOBA
You can do this
你可以这样做
three_hours = 3600*3 # in seconds
if c.total_seconds() >= three_hours:
# do stuff
回答by NightShadeQueen
You can also just compare to another timedelta object
您也可以与另一个 timedelta 对象进行比较
import datetime
if c >= datetime.timedelta(hours=3):
#do something