Python time zone display

161 Views Asked by At

I'm not sure if this is possible but here's the question:

In python, is it possible to get a variable that shows the timezone relative to UTC time? For example, EST would be shown as -5, PST as -8.

Thanks

2

There are 2 best solutions below

1
On

Not sure what you are asking exactly. Hope this may help!,You can use the datetime module . Adapted from http://docs.python.org/library/datetime.html#datetime.tzinfo.fromutc

from datetime import tzinfo, timedelta, datetime

class FixedOffset(tzinfo):
    def __init__(self, offset):
        self.__offset = timedelta(hours=offset)
        self.__dst = timedelta(hours=offset-1)
        self.__name = ''

def utcoffset(self, dt):
    return self.__offset

def tzname(self, dt):
    return self.__name

def dst(self, dt):
    return self.__dst

print datetime.now()
print datetime.now(FixedOffset(9))

Gives:

 2011-03-12 00:28:32.214000
 2011-03-12 14:28:32.215000+09:00
0
On

You can strip times with timezones very easy using the parsedate_tz function from email.utils.

from email.utils import parsedate_tz
import time

datetuple = parsedate_tz('Mon 4 jun 2012 12:34:56 +0700')
print datetuple
print '%s; offset: %s' % (time.strftime('%d-%m-%Y %H:%M', datetuple[:9]),
                          datetuple[9] / 3600.0)