Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading