Get country code for timezone using pytz?

大憨熊 提交于 2021-02-07 11:27:15

问题


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


回答1:


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'



回答2:


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'.



来源:https://stackoverflow.com/questions/13020690/get-country-code-for-timezone-using-pytz

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