How to convert local time string to UTC?

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

    First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See documentation for datetime.strptime for information on parsing the date string.

    Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.

    Finally, use datetime.astimezone() method to convert the datetime to UTC.

    Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

    import pytz, datetime
    local = pytz.timezone ("America/Los_Angeles")
    naive = datetime.datetime.strptime ("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
    local_dt = local.localize(naive, is_dst=None)
    utc_dt = local_dt.astimezone(pytz.utc)
    

    From there, you can use the strftime() method to format the UTC datetime as needed:

    utc_dt.strftime ("%Y-%m-%d %H:%M:%S")
    

提交回复
热议问题