Setting windows/win32 timezone from python

Discussion in 'Python' started by jrhastings@gmail.com, Sep 7, 2006.

  1. Guest

    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
    , Sep 7, 2006
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Neo
    Replies:
    3
    Views:
    598
    Ekkehard Morgenstern
    Nov 13, 2003
  2. asaf
    Replies:
    3
    Views:
    6,117
    =?ISO-8859-1?Q?Arne_Vajh=F8j?=
    Sep 11, 2006
  3. axrock
    Replies:
    8
    Views:
    930
    Roedy Green
    Mar 25, 2009
  4. Will  Rogers
    Replies:
    0
    Views:
    159
    Will Rogers
    May 16, 2006
  5. Ami
    Replies:
    5
    Views:
    259
Loading...

Share This Page