How to pick a timezone based on UTC offset?

你。 提交于 2021-02-05 06:21:33

问题


i've got a silly problem. I'm parsing Facebook user data, and I get the timezone as a number:

timezone: The user's timezone offset from UTC

For me ('America/Argentina/Buenos_Aires') it's -3.

Now, how can I convert that number to a pytz.timezone?

Thank you!


回答1:


There's not a 1:1 correspondence, so there's no way to do it without making some assumptions that are bound to be invalid.

You can create your own tzinfo class that encodes the offset directly without trying to tie it back to a zone.




回答2:


As @Mark Ransom said, multiple pytz.timezone may have the same UTC offset at a given date. You could print the mapping for a particular date:

#!/usr/bin/env python
from collections import defaultdict
from datetime import datetime

import pytz # $ pip install pytz

dt = datetime.now(pytz.utc) # current time in UTC
zone_names = defaultdict(list)
for tz in pytz.common_timezones:
    zone_names[dt.astimezone(pytz.timezone(tz)).utcoffset()].append(tz)

for offset, zone in sorted(zone_names.items()):
    print("%.1f %s" % (offset.total_seconds() / 3600, zone))
# -> -11.0 ['Pacific/Midway', 'Pacific/Niue', 'Pacific/Pago_Pago']
# ...



回答3:


You can use tzinfo.tzname to get the zone name.



来源:https://stackoverflow.com/questions/11657273/how-to-pick-a-timezone-based-on-utc-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!