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:
JavaScript
x
7
1
from datetime import datetime, timedelta
2
3
format = "%Y-%m-%dT%H:%M:%S.000Z"
4
inctime='2022-03-21T19:55:23.577Z'
5
6
time=datetime.strptime(inctime,formato2)
7
Error:
JavaScript
1
8
1
Traceback (most recent call last):
2
File "<stdin>", line 1, in <module>
3
File "C:Usersuser1AppDataLocalProgramsPythonPython310lib_strptime.py", line 568, in _strptime_datetime
4
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
5
File "C:Usersuser1AppDataLocalProgramsPythonPython310lib_strptime.py", line 349, in _strptime
6
raise ValueError("time data %r does not match format %r" %
7
ValueError: time data '2022-03-21T19:55:23.577Z' does not match format '%Y-%m-%dT%H:%M:%S.000Z'
8
Advertisement
Answer
Your code wasn’t reading the microseconds properly. You can read microseconds with %f
Try using this code, this will fix the issue:
JavaScript
1
8
1
from datetime import datetime, timedelta
2
3
4
inctime='2022-03-21T19:55:23.577Z'
5
format = "%Y-%m-%dT%H:%M:%S.%fZ"
6
7
time = datetime.strptime(inctime,format)
8