Datetime.strptime format for 2022-08-24T04:57:17.065000+00:00

Question:

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.

Asked By: Jack tileman

||

Answers:

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)
Answered By: Mark Tolonen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.