How to convert local time string to UTC?

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

    import time
    
    import datetime
    
    def Local2UTC(LocalTime):
    
        EpochSecond = time.mktime(LocalTime.timetuple())
        utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)
    
        return utcTime
    
    >>> LocalTime = datetime.datetime.now()
    
    >>> UTCTime = Local2UTC(LocalTime)
    
    >>> LocalTime.ctime()
    
    'Thu Feb  3 22:33:46 2011'
    
    >>> UTCTime.ctime()
    
    'Fri Feb  4 05:33:46 2011'
    

提交回复
热议问题