How to convert timezone to country code in Python?
我用过这个
1 | from pytz import country_timezones |
但它不包括以下时区
Africa/Asmera, Africa/Timbuktu, America/Argentina/ComodRivadavia, America/Atka, America/Buenos_Aires, America/Catamarca, America/Coral_Harbour, America/Cordoba, America/Ensenada, America/Fort_Wayne, America/Indianapolis, America/Jujuy, America/Knox_IN, America/Louisville, America/Mendoza, America/Montreal, America/Porto_Acre, America/Rosario, America/Shiprock, America/Virgin, Antarctica/South_Pole, Asia/Ashkhabad, Asia/Calcutta, Asia/Chongqing, Asia/Chungking, Asia/Dacca, Asia/Harbin, Asia/Istanbul, Asia/Kashgar, Asia/Katmandu, Asia/Macao, Asia/Saigon, Asia/Tel_Aviv, Asia/Thimbu, Asia/Ujung_Pandang, Asia/Ulan_Bator, Atlantic/Faeroe, Atlantic/Jan_Mayen, Australia/ACT, Australia/Canberra, Australia/LHI, Australia/NSW, Australia/North, Australia/Queensland, Australia/South, Australia/Tasmania, Australia/Victoria, Australia/West, Australia/Yancowinna, Brazil/Acre, Brazil/DeNoronha, Brazil/East, Brazil/West, CET, CST6CDT, Canada/Atlantic, Canada/Central, Canada/East-Saskatchewan, Canada/Eastern, Canada/Mountain, Canada/Newfoundland, Canada/Pacific, Canada/Saskatchewan, Canada/Yukon, Chile/Continental, Chile/EasterIsland, Cuba, EET, EST, EST5EDT, Egypt, Eire, Europe/Belfast, Europe/Nicosia, Europe/Tiraspol, GB, GB-Eire, Greenwich, HST, Hongkong, Iceland, Iran, Israel, Jamaica, Japan, Kwajalein, Libya, MET, MST, MST7MDT, Mexico/BajaNorte, Mexico/BajaSur, Mexico/General, NZ, NZ-CHAT, Navajo, PRC, PST8PDT, Pacific/Ponape, Pacific/Samoa, Pacific/Truk, Pacific/Yap, Poland, Portugal, ROC, ROK, Singapore, Turkey, UCT, US/Alaska, US/Aleutian, US/Arizona, US/Central, US/East-Indiana, US/Eastern, US/Hawaii, US/Indiana-Starke, US/Michigan, US/Mountain, US/Pacific, US/Samoa, UTC, Universal, W-SU, WET, Zulu
如何将这些时区转换为国家/地区代码?
你无法做你想做的事。或者,你可以,但你会得到你得到的结果,而不是你想要的结果。简而言之,如果你要求"使用祖鲁族的国家",并且没有国家使用祖鲁语,你将无法找到任何东西。更详细......
正如国家信息文件所说:
A mechanism is provided to access the timezones commonly in use for a particular country, looked up using the ISO 3166 country code.
但是,
无论如何,这是你如何识别使用给定时区的国家,如下所示:
1 2 | {country for country, timezones in country_timezones.items() if timezone in timezones} |
如果您需要执行大量这些查找,您当然可以构建自己的dict以使其更快更简单:
1 2 3 4 | timezone_countries = {} for country, timezones in country_timezones.items(): for timezone in timezones: timezone_countries.setdefault(timezone, set()).add(country) |
现在它只是:
1 | timezone_countries[timezone] |
但无论哪种方式,你可能得到一个空集,或一组3个国家,而不是1.如果数据库实际上说有0或3个国家使用该时区,那就是你要得到的。