How to format this datetime
A library is returning this timestamp:
2022-01-11T11:23:50.457-0500
i'd like to format it to UTC like this:
2022-01-11 16:23:50.457
Is there a simple way of doing this?
Solution 1:
If you already have a datetime.datetime
object you could do
datetime_obj.strftime('%Y-%m-%d %H:%M:%S.%f')
If all you have is a string you can do
from datetime import datetime, timezone
datetime_obj = datetime.strptime(
'2022-01-11T11:23:50.457-0500',
'%Y-%m-%dT%H:%M:%S.%f%z',
)
datetime_obj.astimezone(tz=timezone.utc).strftime('%Y-%m-%d %H:%M:%S.%f')
Here's the doc for the parsing
Here's the doc for changing the timezeone