In Python 检查当前时间是否小于特定时间?

In Python check if current time is less than specific time?

在 Python 脚本中,我希望它在执行之前检查它是否在世界标准时间上午 9 点之前,以便它可以做一些特定的事情。

我想知道执行此操作的最佳方法是检查时间以确保脚本是每天上午 9 点之前 运行?请记住,代码可能 运行ning 在具有不同时区的不同机器上。

谢谢

datetime 模块应该对您很有帮助。尝试如下操作:

>>> d = datetime.datetime.utcnow()
>>> print d
2015-06-17 11:39:48.585000
>>> d.hour
11
>>> if d.hour < 9:
        print "Run your code here"
# nothing happens, it's after 9:00 here.
>>> 

你试过这个吗

在所有计算机中将时间转换为 UTC,然后将其与您要开始的时间进行比较

from datetime import datetime

now_UTC = datetime.utcnow() # Get the UTC time

# check for the condition
if(now_UTC.hour < 9):
    do something()

通过在线阅读,我得出了这个答案,我看起来不是最有效的,但似乎可以完成工作:

import datetime
import pytz

utc = pytz.utc
loc_dt = utc.localize(datetime.datetime.today().replace(hour=9, minute=0))

today = utc.localize(datetime.datetime.today())

if loc_dt < today:
    print("Go")

获取 UTC 的当前时间:

>>> import time
>>> time.gmtime().tm_hour
15