How to solve datetime format error "time data %r does not match format %r"?

Question:

I’m trying to convert a date from string format to a datetime format. I think that I’m using the right format, but the error is still raised.

Code example:

from datetime import datetime, timedelta

format = "%Y-%m-%dT%H:%M:%S.000Z"
inctime='2022-03-21T19:55:23.577Z'

time=datetime.strptime(inctime,formato2)

Error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:Usersuser1AppDataLocalProgramsPythonPython310lib_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:Usersuser1AppDataLocalProgramsPythonPython310lib_strptime.py", line 349, in _strptime
raise ValueError("time data %r does not match format %r" %
ValueError: time data '2022-03-21T19:55:23.577Z' does not match format '%Y-%m-%dT%H:%M:%S.000Z'
Asked By: Richard

||

Answers:

I think this should work.

from datetime import datetime, timedelta

format_data = "%Y-%m-%dT%H:%M:%S.%fZ"
inctime='2022-03-21T19:55:23.577Z'

time=datetime.strptime(inctime,format_data)

print(time)

The output:

2022-03-21 19:55:23.577000
Answered By: Lion Lai

Your code wasn’t reading the microseconds properly. You can read microseconds with %f

Try using this code, this will fix the issue:

from datetime import datetime, timedelta


inctime='2022-03-21T19:55:23.577Z'
format = "%Y-%m-%dT%H:%M:%S.%fZ"

time = datetime.strptime(inctime,format)
Answered By: Kawish Qayyum