Setting windows/win32 timezone from python

jrhastings at jrhastings at
Thu Sep 7 07:38:20 CEST 2006

I know there are many threads on this topic but I haven't yet found an
answer to this question.  I'd like to map from a utc to a local time in
an arbitrary timezone (not necessary the default local timezone).

To do this on UNIX is relatively straightforward by setting the TZ
environment variable (and calling time.tzset()).  On Windows, one can
get close to the answer using the pytz module (to load the timezone
based on the standard UNIX names like US/Eastern and Australia/Sydney).
 However, the mapping from utc -> local time won't have the correct
notion of DST for the utc you specify because the OS only knows about
the machine's true localtime.  I believe that the only way to really
get the right answer is to temporarily set the machine's local
timezone, which is the standard UNIX approach.

Here's something that _almost_ works in Windows:

import datetime, pytz
d = datetime.datetime.fromtimestamp(1143408899,
d.strftime("%Y%m%d %H:%M:%S")

-> 20060327 07:34:59, but it _should_ be 08:34:59

Here's code that does work in UNIX.

import datetime
import os
import time

tz_orig = os.environ['TZ']

# this code only works on unix
def utc_to_date_time(utc, tz=tz_orig):

        if (tz != tz_orig):
            os.environ['TZ'] = tz

        dt = datetime.datetime.fromtimestamp(utc)
        return (dt.strftime("%Y%m%d"), dt.strftime("%H%M%S"))


        if (os.environ['TZ'] != tz_orig):
            os.environ['TZ'] = tz_orig


- Joe

More information about the Python-list mailing list