python
data_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError: Event 模型验证错误:timestamp 不是有效的 datetime,日期分隔符错误,应为 'T' 或空格
pydantic_core._pydantic_core.ValidationError: 1 validation error for Event timestamp Input should be a valid datetime, invalid date separator, expected 'T' or ' ' [type=datetime_parsing, input_value='2024-01-15_10:30:00', input_type=str]
ID: python/pydantic-validation-error-datetime-parsing
80%修复率
86%置信度
0证据数
2024-09-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
datetime 字符串使用了无效的分隔符(如下划线)。Pydantic v2 使用 RFC 3339 / ISO 8601 解析,要求日期与时间之间用 'T' 或空格分隔。
English
The datetime string uses an invalid separator (e.g. underscore). Pydantic v2 uses RFC 3339 / ISO 8601 parsing and requires 'T' or a space between date and time.
解决方案
-
95% 成功率
value = '2024-01-15_10:30:00'.replace('_', 'T', 1) -
92% 成功率
from datetime import datetime from pydantic import BaseModel, field_validator class Event(BaseModel): timestamp: datetime @field_validator('timestamp', mode='before') @classmethod def parse_dt(cls, v): if isinstance(v, str): return datetime.strptime(v, '%Y-%m-%d_%H:%M:%S') return v
无效尝试
常见但无效的做法:
-
60% 失败
strptime works but bypasses Pydantic validation, so type errors surface later as AttributeError.
-
75% 失败
Loses timezone-aware comparison and arithmetic capabilities.