如何解决日期时间格式错误“时间数据 %r 与格式 %r 不匹配”?
我正在尝试将日期从字符串格式转换为日期时间格式。我认为我使用了正确的格式,但仍然出现错误。
代码示例:
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)
错误:
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'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码没有正确读取微秒。您可以使用
%f
读取微秒尝试使用此代码,这将解决问题:
Your code wasn't reading the microseconds properly. You can read microseconds with
%f
Try using this code, this will fix the issue:
我认为这应该有效。
输出:
I think this should work.
The output: