Search code examples
pythontimezonepytz

Pytz correct offset of timezones with daylight


I have a function that return a list of cities + theirs UTC offsets

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)

and ordered by offsets:

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

And get the next list:

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

But for example Shanghai is UTC/GMT +8 hours. Is it something with daylight or where is a problem? How can I return a correct timezones list depending on daylight?


Solution

  • It is incorrect to pass UTC time to tzone.localize() unless tzone is UTC. Use tzone.fromutc(std_date) instead.