【问题标题】:pytz: getting all timezones, where now is specific timepytz:获取所有时区,现在是特定时间
【发布时间】:2012-06-12 09:51:34
【问题描述】:

在 DB 中,我有表 (User),它为该用户存储时区(作为字符串值,例如:“Europe/Oslo”)。 现在,我需要获取所有用户,例如现在的当地时间:上午 9 点。

有没有什么好的方法可以做到这一点,而无需对所有用户进行循环?如果pytz 能够返回时区列表,现在时间是上午 9 点,我可以使用简单的IN SQL 语句。

【问题讨论】:

    标签: python timezone pytz


    【解决方案1】:
    import datetime
    import pytz
    
    now = datetime.now(pytz.utc)
    # datetime.datetime(2012, 6, 8, 10, 31, 58, 493905, tzinfo=<UTC>)
    
    [tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 9]
    # ['Atlantic/Cape_Verde']
    
    [tz for tz in pytz.common_timezones_set if now.astimezone(pytz.timezone(tz)).hour == 12]
    # returns a list of 45 timezones, 'Europe/Oslo' included
    

    【讨论】:

    • 太棒了!正是我想要的。
    猜你喜欢
    • 2022-01-09
    • 2012-11-27
    • 2017-08-05
    • 2016-03-12
    • 2018-10-20
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    相关资源
    最近更新 更多