How to convert local time string to UTC?

后端 未结 23 1704
离开以前
离开以前 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 04:52

    Thanks @rofly, the full conversion from string to string is as follows:

    time.strftime("%Y-%m-%d %H:%M:%S", 
                  time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", 
                                                        "%Y-%m-%d %H:%M:%S"))))
    

    My summary of the time/calendar functions:

    time.strptime
    string --> tuple (no timezone applied, so matches string)

    time.mktime
    local time tuple --> seconds since epoch (always local time)

    time.gmtime
    seconds since epoch --> tuple in UTC

    and

    calendar.timegm
    tuple in UTC --> seconds since epoch

    time.localtime
    seconds since epoch --> tuple in local timezone

提交回复
热议问题