Search code examples
pythondatetimedatetime-formatiso8601

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


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.


Solution

  • 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)