使用pytz获取时区的国家代码?

20
我正在使用pytz库。我已经阅读了整个文档,但没有找到如何实现此功能的说明。
我有一个时区:美国/芝加哥。我想要的只是获取该时区对应的国家代码:US。
文档显示可以做相反的操作,例如:
>>> country_timezones('ch')
['Europe/Zurich']
>>> country_timezones('CH')
['Europe/Zurich']

但我需要用相反的方式做。

这是否可以使用Python完成,使用pytz(或任何其他方法)?

2个回答

26
你可以使用来自 pytzcountry_timezones 对象并生成一个反向映射:
你可以使用来自pytzcountry_timezones对象,并生成一个反向映射:
from pytz import country_timezones

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

现在只需使用生成的字典:

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

@J.F.Sebastian,你之前最后一句话是什么意思?那些时区不在哪里? - Snowman
所有在pytz中定义的时区都对应一个国家。因此,它不会出错。 - jsalonen
@mohabitar:这些时区不在country_timezones值中,因此使用country_timezones生成的timezone_country将会为UTC、US/Central等产生KeyError。 - jfs
@J.F.Sebastian,那我在访问该值之前应该检查timezone_country中是否包含'Europe/Zurich'吗? - Snowman
1
如果您使用不在country_timezones值中的时区,则需要其他解决方案。 - jfs
显示剩余4条评论

6
这很容易。你有一个字典(mapping),它将每个国家映射到一个时区列表。你想将每个列表成员映射回到字典(dict)中。 与其只是给出答案,不如看看如何得到它。
首先,如果你只有一个将每个国家映射到单个时区的字典,那么这将是一个简单的反向映射:
timezone_countries = {timezone: country 
                      for country, timezone in country_timezones.iteritems()}

但是这样做行不通;你有一个映射到时区列表的映射,你希望该列表中的每个时区都能映射回该国家。那个英文描述中的"each timezone in that list"很容易翻译成Python代码:
timezone_countries = {timezone: country 
                      for country, timezones in country_timezones.iteritems()
                      for timezone in timezones}

下面是它的实际应用:

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

附注:您没有提及Python 2与3之间的区别,因此我假设您使用的是2。如果您使用的是3,请将iteritems更改为items,输出结果将是'CH'而不是u'CH'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接