How to convert local time string to UTC?

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

    This thread seems to be missing an option available since Python 3.6: datetime.astimezone(tz=None) can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.

    from datetime import datetime, timezone
    s = "2008-09-17 14:02:00"
    
    # to datetime object:
    dt = datetime.fromisoformat(s) # Python 3.7
    
    # I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
    dt = dt.astimezone()
    print(dt)
    # 2008-09-17 14:02:00+02:00
    
    # ...and to UTC:
    dtutc = dt.astimezone(timezone.utc)
    print(dtutc)
    # 2008-09-17 12:02:00+00:00
    

    There is one caveat though, see astimezone(None) gives aware datetime, unaware of DST.

提交回复
热议问题