Categories
Python Answers

How to convert timestamps with offset to datetime obj using Python’s strptime?

Spread the love

Sometimes, we want to convert timestamps with offset to datetime obj using Python’s strptime method.

In this article, we’ll look at how to convert timestamps with offset to datetime obj using Python’s strptime method.

How to convert timestamps with offset to datetime obj using Python’s strptime?

To convert timestamps with offset to datetime obj using Python’s strptime method, we can call isoformat after parsing the datetime string.

For instance, we write:

from datetime import datetime

time_str = "2021-07-24T23:14:29-07:00"
dt_aware = datetime.fromisoformat(time_str)
print(dt_aware.isoformat('T'))

We call datetime.fromisoformat method with the time_str datetime string.

Then we call isoformat with T to put the 'T‘ between the date and the time of the returned datetime string.

Therefore, print will print '2021-07-24T23:14:29-07:00'.

Conclusion

To convert timestamps with offset to datetime obj using Python’s strptime method, we can call isoformat after parsing the datetime string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *