Python中datetime.strptime报ValueError:时间格式不匹配问题排查
datetime.strptime格式匹配失败的原因分析
运行以下代码时抛出
ValueError异常,提示信息为:"time data '2023-03-16T21:30:00.0000000Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'",请问错误原因是什么?
相关代码:
from datetime import datetime date_string = '2023-03-16T21:30:00.0000000Z' day_of_month_in_result = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ').day print(day_of_month_in_result)
错误原因
Python标准库中datetime.strptime的%f格式符仅支持解析最多6位的微秒数值,但你的日期字符串里秒数后的小数部分有7位(0000000),超出了%f的解析上限,导致格式完全不匹配,触发ValueError。
解决方法
- 截断多余的小数位:手动把字符串的最后一位小数去掉,让微秒部分保持6位:
from datetime import datetime date_string = '2023-03-16T21:30:00.0000000Z' # 截取到倒数第二位,再拼接Z fixed_date = date_string[:-2] + 'Z' day = datetime.strptime(fixed_date, '%Y-%m-%dT%H:%M:%S.%fZ').day print(day) # 输出16
- 使用第三方库自动解析:用
dateutil.parser可以兼容这种超过6位微秒的格式(需要先执行pip install python-dateutil安装库):
from dateutil import parser date_string = '2023-03-16T21:30:00.0000000Z' day = parser.parse(date_string).day print(day) # 输出16
内容的提问来源于stack exchange,提问作者user1438082
相关产品推荐
相关产品推荐

