How to convert local time string to UTC?

后端 未结 23 1631
离开以前
离开以前 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:53

    Briefly, to convert any datetime date to UTC time:

    from datetime import datetime
    
    def to_utc(date):
        return datetime(*date.utctimetuple()[:6])
    

    Let's explain with an example. First, we need to create a datetime from the string:

    >>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")
    

    Then, we can call the function:

    >>> to_utc(date)
    datetime.datetime(2011, 2, 12, 1, 33, 54)
    

    Step by step how the function works:

    >>> date.utctimetuple()
    time.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)
    >>> date.utctimetuple()[:6]
    (2011, 2, 12, 1, 33, 54)
    >>> datetime(*date.utctimetuple()[:6])
    datetime.datetime(2011, 2, 12, 1, 33, 54)
    

提交回复
热议问题