python-3.xdatetimetimezonetimestamp-with-timezone

How can I convert the time stamp with timezone info to utc time in python


I have the time string like this "2023-09-06T22:02:44-07:00", which is obtained through calling

datetime.now().astimezone().isoformat(timespec='seconds')

My question is how to convert the time string "2023-09-06T22:02:44-07:00" to utc time? Basically how to convert it so that -07:00 will be +00:00?


Solution

  • You can first use the fromisoformat method to convert the timestamp string to a datetime object, then call the astimezone(timezone.utc) method to convert it to UTC timezone, and output the converted timestamp in ISO format with isoformat:

    from datetime import datetime, timezone
    
    t = "2023-09-06T22:02:44-07:00"
    print(datetime.fromisoformat(t).astimezone(timezone.utc).isoformat(timespec='seconds'))
    

    This outputs:

    2023-09-07T05:02:44+00:00