Convert UTC datetime string to local datetime

后端 未结 13 1202
醉话见心
醉话见心 2020-11-22 05:37

I\'ve never had to convert time to and from UTC. Recently had a request to have my app be timezone aware, and I\'ve been running myself in circles. Lots of information on co

13条回答
  •  野的像风
    2020-11-22 06:07

    You can use calendar.timegm to convert your time to seconds since Unix epoch and time.localtime to convert back:

    import calendar
    import time
    
    time_tuple = time.strptime("2011-01-21 02:37:21", "%Y-%m-%d %H:%M:%S")
    t = calendar.timegm(time_tuple)
    
    print time.ctime(t)
    

    Gives Fri Jan 21 05:37:21 2011 (because I'm in UTC+03:00 timezone).

提交回复
热议问题