2011-02-08 56 views
0

我使用babel和pytz來獲取時區。然而,對於美國大部分地區而言,它映射到的下拉框不太有用:更好的Python日期時間顯示?

「America/New_York」顯示「Eastern Time」, 「America/Nipigon」還顯示「Eastern Time」。

有沒有辦法做這種轉換來添加城市信息?其他時區似乎沒有問題,如「亞洲/雅加達」轉換爲「印度尼西亞(雅加達)時間」

回答

2

適用於Babel 0.9.5和Pytz 2010b。

py.tz

#!/usr/bin/env python 

import pytz 
import babel.dates 

tz = pytz.timezone('America/New_York') 
print babel.dates.get_timezone_location(tz) 

輸出

$ python tz.py 
United States (New York) Time 

你是如何運行的呢?什麼版本?


如果您遇到您擁有的版本,那麼爲什麼不僅使用洲/城市條目?

這是您的起點。它決定了大陸和城市,所以你可以根據需要進行格式化。

tzs.py

#!/usr/bin/env python 

import pytz 
import babel.dates 
import re 

country_timezones = {} 
for (country, tzlist) in pytz.country_timezones.iteritems(): 
    country_name = pytz.country_names[country] 
    cities = [] 
    for timezone in tzlist: 
     # remove continent 
     city = re.sub(r'^[^/]*/', r'', timezone) 
     # Argentina has an extra "Argentina/" on my system (pytz 2010b) 
     city = re.sub(country_name + '/', '', city) 
     # Indiana and North Dakota have different rules by country 
     # change Indiana/Location to Location, Indiana 
     city = re.sub(r'^([^/]*)/(.*)', r'\2, \1', city) 
     # change underscores to spaces 
     city = re.sub(r'_', r' ', city) 
     cities.append(city) 
    country_timezones[country_name] = cities 

for country in sorted(country_timezones): 
    print country 
    for city in sorted(country_timezones[country]): 
     print "\t%s" % (city) 

輸出

Aaland Islands 
     Mariehamn 
Afghanistan 
     Kabul 
... 
Indonesia 
     Jakarta 
     Jayapura 
     Makassar 
     Pontianak 
... 
United States 
     Adak 
     Anchorage 
     Boise 
     Center, North Dakota 
     Chicago 
     Denver 
     Detroit