How can I format date using timezone?


How can I format date using timezone using the epoch time? Using python 2.5
t = time.gmtime(sec)
print time.strftime("%b %d %Y %H:%M:%S", t)
returns Aug 26 2010 16:53:49, which is GMT time

t = time.localtime(sec)
print time.strftime("%b %d %Y %H:%M:%S", t)
returns Aug 26 2010 9:53:49, which is PST

How can I get this in Mountain timezone, any other timezone the user passes in?

Also, where are the list of timezone constants in Python?


Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

markaaaConnect With a Mentor Commented:
The Python standard library doesn't contain timezone information and doesn't have good timezone support. You will need to use a package such as pytz and there are still some platform specific issues. You can get pytz here and they show examples of usage.
jamie_lynnAuthor Commented:
Hi markaaa,

If my localtime is UTC,
In the standard library, is there way determine if daylight savings for Pacific? with this info, i can calculate the offset from GMT.

peprConnect With a Mentor Commented:
As markaaa suggested, you probably should download the pytz (  After installation ('python install' from the directory created from the unzipped archive).

Try the snippet below. It generates the files with timezones, and it shows the same UTC time naturally for different timezones.  It shows the following on my machine:

Generating 'all_timezones.txt'
Generating 'common_timezones.txt'
Generating 'US_timezones.txt'
UTC 2010-08-27 09:52:36 UTC+0000
Australia/Sydney 2010-08-27 19:52:36 EST+1000
Pacific/Auckland 2010-08-27 21:52:36 NZST+1200
import datetime
import pytz
import time

fname = 'all_timezones.txt'
print 'Generating', repr(fname)
f = open(fname, 'w')
for z in pytz.all_timezones:
    f.write(repr(z) + '\n')  # repr() to wrap in quotes

fname = 'common_timezones.txt'
print 'Generating', repr(fname)
f = open(fname, 'w')
for z in pytz.common_timezones:
    f.write(repr(z) + '\n')

fname = 'US_timezones.txt'
print 'Generating', repr(fname)
f = open(fname, 'w')
for z in pytz.country_timezones('US'):
    f.write(repr(z) + '\n')

fmt = '%Y-%m-%d %H:%M:%S %Z%z'

utc_dt = pytz.utc.localize(datetime.datetime.utcnow())
print 'UTC', utc_dt.strftime(fmt)

au_tz = pytz.timezone('Australia/Sydney')
au_dt = au_tz.normalize(utc_dt.astimezone(au_tz))
print 'Australia/Sydney', au_dt.strftime(fmt)

pa_tz = pytz.timezone('Pacific/Auckland')
pa_dt = pa_tz.normalize(utc_dt.astimezone(pa_tz))
print 'Pacific/Auckland', pa_dt.strftime(fmt)

Open in new window

All Courses

From novice to tech pro — start learning today.