【问题标题】:Compare two times (without dates) using the Python time module使用 Python 时间模块比较两次(不包括日期)
【发布时间】:2017-07-04 20:15:18
【问题描述】:

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

我想创建两次。

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

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

【问题讨论】:

  • 您的问题不清楚。无论如何,您需要知道将不知道日期的时间与不同的时区进行比较并不是一个明确定义的问题。特别是使用 DST(夏令时)时,时区的 utc 偏移量可能取决于日期。
  • @AdrienMatissart 澄清一下,我只想比较两次(不是日期)。时间 1 是 UTC 20:30。时间 2 可以是任何其他时间(例如 datetime.now().hour)。我显然想捕获 Time 2 的 tzinfo,但我不清楚如何做到这一点。
  • 同样,要“将 time2 调整为 UTC”,您需要一个时区和一个日期。例如,7 月柏林的 10:00 是 08:00 UTC,但在 12 月,它将是 09:00 UTC。
  • 一些代码可能会很有帮助

标签: python datetime time compare utc


【解决方案1】:

事实证明,@AdrienMatissart 的评论是解决这个简单问题所需的线索。诀窍是在世界标准时间 20:30 为今天的日期创建一个日期时间对象。然后为当前时间创建另一个日期时间对象。通过将当前系统时间本地化为 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多