How to convert local time string to UTC?

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

    I've had the most success with python-dateutil:

    from dateutil import tz
    
    def datetime_to_utc(date):
        """Returns date in UTC w/o tzinfo"""
        return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date
    

提交回复
热议问题