Search code examples
pythonpython-3.xdatetimedatetime-formatpython-datetime

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


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:\Users\user1\AppData\Local\Programs\Python\Python310\lib\_strptime.py", line 568, in _strptime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\_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'

Solution

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