tags:

views:

92

answers:

1

Is this the correct way to convert a UTC string into local time allowing for daylight savings? It looks ok to me but you never know :)

import time
UTC_STRING = "2010-03-25 02:00:00"
stamp = time.mktime(time.strptime(UTC_STRING,"%Y-%m-%d %H:%M:%S"))
stamp -= time.timezone
now   = time.localtime()
if now[8] == 1:
    stamp += 60*60
elif now[8] == -1:
    stamp -= 60*60
print 'UTC: ', time.gmtime(stamp)
print 'Local: ', time.localtime(stamp)

--- Results from New Zealand (GMT+12 dst=1) ---

UTC:  (2010, 3, 25, 2, 0, 0, 3, 84, 0)
Local:  (2010, 3, 25, 15, 0, 0, 3, 84, 1)
+4  A: 

timezone related calculations are not trivial and there are already good libraries available e.g. use pytz, using that you will be able to convert from any timezone to any other timezone with confidence. usage is as simple as this

>>> warsaw = pytz.timezone('Europe/Warsaw')
>>> loc_dt1 = warsaw.localize(datetime(1915, 8, 4, 23, 59, 59), is_dst=False)
Anurag Uniyal
I would like to hang a poster where I work reading "clock programming is not trivial!"
Arrieta
I have tested using pytz. The only problem I see is that you need to know the standard timezone string in order to set the timezone. However when running across multiple O/S's especially including Windows (which has to have the strangest way of defining the timezone), and after several hours of testing, this code snipit was the only one I could get to work consistently across platforms.
Steve
but these are standard string and there need to be way to tell which timezone
Anurag Uniyal