Peabrain
Peabrain

Reputation: 589

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

Upvotes: 3

Views: 5730

Answers (2)

Michael Dorner
Michael Dorner

Reputation: 20125

If you have the chance to work with standardized timestamps like yours, I highly recommend to use datetime.fromisoformat:

from datetime import datetime
d = datetime.fromisoformat('2021-11-24T16:05:51.399+0000')

It is so much more robust and makes so much sense.

Upvotes: 2

user459872
user459872

Reputation: 24562

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)

Upvotes: 4

Related Questions