1

We have the following string in a variable:

date_variable = "2022-08-24T04:57:17.065000+00:00"

We would like to convert this to datetime.

The following does not work:

timestamp_formatted = datetime.strptime(date_variable, '%Y-%m-%d%H:%M:%S.%f+%z')

Please help.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Jack tileman
  • 813
  • 2
  • 11
  • 26

1 Answers1

3

You left out the T and %z includes the sign of the time zone offset so remove the +:

from datetime import datetime

date_variable = "2022-08-24T04:57:17.065000+00:00"
#                          ^

timestamp_formatted = datetime.strptime(date_variable, '%Y-%m-%dT%H:%M:%S.%f%z')
print(repr(timestamp_formatted))

Output:

datetime.datetime(2022, 8, 24, 4, 57, 17, 65000, tzinfo=datetime.timezone.utc)
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251