pythontimestamppython-datetime

Timestamp string to datetime (python)


I have this timestamp string:

x = 2021-11-24T16:05:51.399+0000

I am struggling to get the parsing to pass after the decimal point. Here is my attempt so far:

datetime.datetime.strptime(x,"%Y-%m-%dT%H:%M:%S.%f+")

Current error running this line:

ValueError: unconverted data remains: 0000

Solution

  • Add %z at the end of the format to match UTC offset in the form ±HHMM[SS[.ffffff]] (empty string if the object is naive).

    >>> from datetime import datetime
    >>>
    >>> x = '2021-11-24T16:05:51.399+0000'
    >>> datetime.strptime(x,"%Y-%m-%dT%H:%M:%S.%f%z")
    datetime.datetime(2021, 11, 24, 16, 5, 51, 399000, tzinfo=datetime.timezone.utc)