views:

532

answers:

3

Hi,

Is there an elegant way to display the current time in another time zone?

I would like to have something with the general spirit of:

cur=<Get the current time, perhaps datetime.datetime.now()>
print "Local time   ", cur
print "Pacific time ", <something like cur.tz('PST')>
print "Israeli time ", <something like cur.tz('IST')>

Any ideas?

+4  A: 

You could use the pytz library:

>>> from datetime import datetime, timedelta
>>> from pytz import timezone
>>> import pytz
>>> utc = pytz.utc
>>> utc.zone
'UTC'
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> fmt = '%Y-%m-%d %H:%M:%S %Z%z'

>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print loc_dt.strftime(fmt)
2002-10-27 06:00:00 EST-0500

>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
Andre Miller
+1 Exactly what I needed, Thanks!
Adam Matan
A: 

You can check this question.

Or try using pytz. Here you can find an installation guide with some usage examples.

Guillem Gelabert
A: 

One way, through the timezone setting of the C library, is

>>> cur=time.time()
>>> os.environ["TZ"]="US/Pacific"
>>> time.tzset()
>>> time.strftime("%T %Z", time.localtime(cur))
'03:09:51 PDT'
>>> os.environ["TZ"]="GMT"
>>> time.strftime("%T %Z", time.localtime(cur))
'10:09:51 GMT'
Martin v. Löwis
This only works in Unix according to the documentation. Not sure if that makes a difference here though.
Andre Miller