问题
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