Get country code for timezone using pytz?

python, pytz

Solution

You can use the `country_timezones` object from `pytz` and generate an inverse mapping:

from pytz import country_timezones

timezone_country = {}
for countrycode in country_timezones:
    timezones = country_timezones[countrycode]
    for timezone in timezones:
        timezone_country[timezone] = countrycode

Now just use the resulting dictionary:

>>> timezone_country['Europe/Zurich']
u'CH'

Problem

I'm using pytz. I've read through the entire documentation sheet, but didn't see how this could be done. I have a timezone: America/Chicago. All I want is to get the respective country code for this timezone: US. It shows that I can do the opposite, such as: ``` >>> country_timezones('ch') ['Europe/Zurich'] >>> country_timezones('CH') ['Europe/Zurich'] ``` but I need to do it the other way around. Can this be done in Python, using pytz (or any other way for that matter)?

Original source