Pytz: Return Olson Timezone Name From Only A Gmt Offset
Solution 1:
UTC offset by itself may be ambiguous (it may correspond to several timezones that may have different rules in some time period):
#!/usr/bin/env pythonfrom datetime import datetime, timedelta
import pytz # $ pip install pytz
input_utc_offset = timedelta(hours=-4)
timezone_ids = set()
now = datetime.now(pytz.utc) #XXX: use date that corresponds to input_utc_offset instead!for tz inmap(pytz.timezone, pytz.all_timezones_set):
dt = now.astimezone(tz)
tzinfos = getattr(tz, '_tzinfos',
[(dt.tzname(), dt.dst(), dt.utcoffset())])
ifany(utc_offset == input_utc_offset for utc_offset, _, _ in tzinfos):
# match timezones that have/had/will have the same utc offset
timezone_ids.add(tz.zone)
print(timezone_ids)
Output
{'America/Anguilla',
'America/Antigua',
'America/Argentina/Buenos_Aires',
...,
'Cuba',
'EST5EDT',
'Jamaica',
'US/East-Indiana',
'US/Eastern',
'US/Michigan'}
You can't even limit the list using pytz.country_timezones['us']
because it would exclude one of your examples: 'America/Puerto_Rico'
.
If you know coordinates (latitude, longitude); you could get the timezone id from the shape file: you could use a local database or a web-service:
#!/usr/bin/env pythonfrom geopy import geocoders # pip install "geopy[timezone]"
g = geocoders.GoogleV3()
for coords in [(18.4372, -67.159), (41.9782, -71.7679), (61.1895, -149.874)]:
print(g.timezone(coords).zone)
Output
America/Puerto_Rico
America/New_York
America/Anchorage
Note: some local times may be ambiguous e.g., when the time falls back during end of DST transition. You could pass is_dst=None
to .localize()
method to raise an exception in such cases.
Different versions of the tz database may have different utc offset for some timezones at some dates i.e., it is not enough to store UTC time and the timezone id (what version to use depends on your application).
Post a Comment for "Pytz: Return Olson Timezone Name From Only A Gmt Offset"