Better python datetime display?

723 views Asked by At

I'm using babel and pytz to get the time zones. However, for most of America, it maps to something not as helpful in a dropdown box:

"America/New_York" displays "Eastern Time", "America/Nipigon" also displays "Eastern Time".

Is there some way to do this conversion to add city info? other timezones seems okay, like "Asia/Jakarta" converts to "Indonesia (Jakarta) Time"

1

There are 1 answers

0
Mikel On BEST ANSWER

Works for me with Babel 0.9.5 and 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)

output

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

How are you running it? What versions?


If you are stuck with the versions you have, then why not only use the Continent/City entries?

Here's a starting point for you. It determines both the continent and the city, so you can format it however you want.

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)

output

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