How to convert local time string to UTC?

后端 未结 23 1620
离开以前
离开以前 2020-11-22 04:18

How do I convert a datetime string in local time to a string in UTC time?

I\'m sure I\'ve done this before, but can\'t find it and SO will hopefull

23条回答
  •  长发绾君心
    2020-11-22 05:04

    def local_to_utc(t):
        secs = time.mktime(t)
        return time.gmtime(secs)
    
    def utc_to_local(t):
        secs = calendar.timegm(t)
        return time.localtime(secs)
    

    Source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html

    Example usage from bd808: If your source is a datetime.datetime object t, call as:

    local_to_utc(t.timetuple())
    

提交回复
热议问题