How to convert local time string to UTC?

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

    I'm having good luck with dateutil (which is widely recommended on SO for other related questions):

    from datetime import *
    from dateutil import *
    from dateutil.tz import *
    
    # METHOD 1: Hardcode zones:
    utc_zone = tz.gettz('UTC')
    local_zone = tz.gettz('America/Chicago')
    # METHOD 2: Auto-detect zones:
    utc_zone = tz.tzutc()
    local_zone = tz.tzlocal()
    
    # Convert time string to datetime
    local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')
    
    # Tell the datetime object that it's in local time zone since 
    # datetime objects are 'naive' by default
    local_time = local_time.replace(tzinfo=local_zone)
    # Convert time to UTC
    utc_time = local_time.astimezone(utc_zone)
    # Generate UTC time string
    utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')
    

    (Code was derived from this answer to Convert UTC datetime string to local datetime)

提交回复
热议问题