python
data_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError:1 个验证错误(Event) when 输入应为有效的 datetime,日期分隔符无效,应为 '-' [type=datetime_parsing, input_value='2024/01/15', input_type=str]
pydantic_core._pydantic_core.ValidationError: 1 validation error for Event when Input should be a valid datetime, invalid date separator, expected `-` [type=datetime_parsing, input_value='2024/01/15', input_type=str]
ID: python/pydantic-datetime-parsing
80%修复率
87%置信度
0证据数
2024-07-21首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
字符串使用了斜杠分隔符,Pydantic v2 的严格 ISO 解析器拒绝该格式,它期望使用短横线的 ISO 8601 格式。
English
The string uses slash separators that Pydantic v2's strict ISO parser rejects. It expects ISO 8601 with dashes.
解决方案
-
90% 成功率
from pydantic import BaseModel, field_validator from dateutil import parser class Event(BaseModel): when: 'datetime' @field_validator('when', mode='before') @classmethod def parse(cls, v): return parser.parse(v) if isinstance(v, str) else v -
85% 成功率
import re s = re.sub(r'/', '-', '2024/01/15') Event(when=s)
无效尝试
常见但无效的做法:
-
50% 失败
datetime_format only applies to date fields, not datetime, and won't accept time-less strings.
-
60% 失败
Loses validation; downstream code must branch on type.
-
45% 失败
Every call site must remember to convert; easy to miss and inconsistent.