Setting windows/win32 timezone from python

J

jrhastings

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,
pytz.timezone("Australia/Sydney"))
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):

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

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

finally:

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

Thanks,

- Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top