python Python中的一小时差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2571432/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:56:40  来源:igfitidea点击:

One hour difference in Python

pythondatetime

提问by Joel

I have a datetime.datetime property var. I would like to know if it is less than one hour of the current time. Something like

我有一个 datetime.datetime 属性变量。我想知道它是否小于当前时间的一小时。就像是

var.hour<datetime.datetime.today().hour - 1

Problem with the above syntax is that

上述语法的问题在于

datetime.datetime.today().hour

returns a number such as "10" and it is not really a date comparation but more of a numbers comparation.

返回一个数字,例如“10”,它实际上不是日期比较,而是更多的数字比较。

What is the correct syntax?

什么是正确的语法?

Thanks!

谢谢!

Joel

乔尔

回答by Daniel Roseman

Use datetime.timedelta.

使用datetime.timedelta.

var < datetime.datetime.today() - datetime.timedelta(hours=1)

回答by pocoa

You can use dateutil.relativedelta

您可以使用dateutil.relativedelta

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

now = datetime.now()
other_time = now + timedelta(hours=8)
diff = relativedelta(other_time, now)
print diff.hours # 8