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

Time:03-25

I'm trying to convert a date from string format to a datetime format. I thinkt that im using the right format, but the error still raising.

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'

CodePudding user response:

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

CodePudding user response:

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