开发者

Is this the correct way to convert a UTC datetime string into localtime?

开发者 https://www.devze.com 2022-12-25 01:47 出处:网络
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 :)

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)

--- Resul开发者_运维技巧ts 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)


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消