【问题标题】:Pytz correct offset of timezones with daylightPytz 正确的时区偏移与日光
【发布时间】:2015-07-20 04:06:49
【问题描述】:

我有一个函数可以返回城市列表 + 他们的 UTC 偏移量

NOW = datetime.datetime.utcnow()
ZERO = datetime.timedelta(0)

result_list = {}

allowed_city = ['Europe/London', 'Europe/Amsterdam', 'Europe/Helsinki', 'Europe/Moscow', 
'Asia/Yekaterinburg', 'Asia/Novosibirsk', 'Asia/Shanghai', 'Asia/Tokyo']

for tname in allowed_city:
    tzone = pytz.timezone(tname)
    std_date = None
    try:
        for utcdate, info in zip(
                tzone._utc_transition_times, tzone._transition_info):
            utcoffset, dstoffset, tzname = info
            if dstoffset == ZERO:
                std_date = utcdate
            if utcdate > NOW:
                break
    except AttributeError:
        std_date = NOW
    std_date = tzone.localize(std_date)

    key = std_date.strftime('%z')

    result_list[tname] = "%s UTC %s" % (key, tname)

并按偏移量排序:

collections.OrderedDict(sorted(result_list.items(), key=lambda x: x[1]))

并获得下一个列表:

+0000 UTC Europe/London
+0200 UTC Europe/Amsterdam
...
+0900 UTC Asia/Shanghai
+1000 UTC Asia/Tokyo

但例如上海是 UTC/GMT +8 小时。是日光问题还是问题出在哪里?如何根据日光返回正确的时区列表?

【问题讨论】:

    标签: python timezone pytz


    【解决方案1】:

    将 UTC 时间传递给 tzone.localize() 是不正确的,除非 tzone 是 UTC。请改用tzone.fromutc(std_date)

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 1970-01-01
      • 2018-02-12
      • 2011-11-12
      • 2017-04-24
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多