Snowman
Snowman

Reputation: 32091

Get country code for timezone using pytz?

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)?

Upvotes: 20

Views: 19878

Answers (2)

abarnert
abarnert

Reputation: 366103

This is easy. You have a dict mapping each country to a list of timezones. You want to map each list member back to the dict.

Rather than just give the answer, let's see how to get it.

First, if you just had a dict mapping each country to a single timezone, this would be a simple reverse mapping:

timezone_countries = {timezone: country 
                      for country, timezone in country_timezones.iteritems()}

But this won't work; you have a mapping to a list of timezones, and you want each timezone in that list to map back to the country. That English description "each timezone in that list" is trivially translatable to Python:

timezone_countries = {timezone: country 
                      for country, timezones in country_timezones.iteritems()
                      for timezone in timezones}

Here it is in action:

>>> from pytz import country_timezones
>>> timezone_countries = {timezone: country 
                          for country, timezones in country_timezones.iteritems()
                          for timezone in timezones}
>>> timezone_countries['Europe/Zurich']
u'CH'

Side note: You didn't mention Python 2 vs. 3, so I assumed 2. If you're on 3, change iteritems to items, and the output will be 'CH' instead of u'CH'.

Upvotes: 6

jsalonen
jsalonen

Reputation: 30531

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'

Upvotes: 28

Related Questions