使用 Python 时间模块比较两个时间(没有日期)

Compare two times (without dates) using the Python time module

这么简单的事情怎么会这么棘手?

我要创建两次。

Time1 是 UTC 8:30pm (20:30) 的日期未知时间。 Time2 是地球上任何其他时间(小时、分钟、秒)。

正如我所搜索的那样,文档和 Whosebug 示例都使用 datetime 模块并包括创建带时间的日期。我只需要比较两次,如果需要,将 Time2 调整为 UTC。

事实证明,@AdrienMatissart 的评论是解决这个简单问题所需的线索。诀窍是为今天 20:30 UTC 的日期创建一个日期时间对象。然后为当前时间创建另一个 datetime 对象。通过将当前系统时间本地化为 UTC,可以考虑夏令时并可以比较日期时间对象。

import pytz, datetime
UTC_TZ = pytz.utc

# use combine() to create a specific datetime in today's future
end = datetime.datetime.combine(datetime.date.today(), datetime.time(20, 30, tzinfo=UTC_TZ) )

# get the current system datetime and localize to account for daylight savings
right_now = datetime.datetime.now(tz=UTC_TZ)

# then I compare
if end > right_now: 
    # some action