0

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?

intrigued_66
  • 16,082
  • 51
  • 118
  • 189

1 Answers1

3

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 timezone

Speedlulu
  • 331
  • 2
  • 7