简体   繁体   English

使用Python时间模块比较两次(无日期)

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

How could something this simple be this tricky? 这样简单的事情怎么会如此棘手?

I want to create two times. 我想创建两次。

Time1 is a date-unaware time of UTC 8:30pm (20:30). Time1是UTC的不知道日期的时间8:30 pm(20:30)。 Time2 is any other time (hour, minute, second) on the planet. Time2是地球上的任何其他时间(小时,分钟,秒)。

Hard as I've searched, the documentation and the stackoverflow examples all use the datetime module and include creating a date with the time. 正如我所搜索的那样,文档和stackoverflow示例都使用datetime模块,包括使用时间创建日期。 I just need to compare two times and, if needed, adjust Time2 to UTC. 我只需要比较两次,如果需要,将Time2调整为UTC。

It turned out that @AdrienMatissart's comment was the clue needed to figure this simple issue out. 事实证明,@ AdrienMatissart的评论是弄清楚这个简单问题所需的线索。 The trick was to create a datetime object for today's date at 20:30 UTC. 诀窍是在世界标准时间20:30创建今天日期的datetime对象。 Then to create another datetime object for the current time. 然后为当前时间创建另一个datetime对象。 By localizing the current system time to UTC, daylight savings is accounted for and the datetime objects can be compared. 通过将当前系统时间本地化为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM