python
data_error
ai_generated
true
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%Fix Rate
86%Confidence
0Evidence
2024-09-11First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
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.
generic中文
datetime 字符串使用了无效的分隔符(如下划线)。Pydantic v2 使用 RFC 3339 / ISO 8601 解析,要求日期与时间之间用 'T' 或空格分隔。
Workarounds
-
95% success
value = '2024-01-15_10:30:00'.replace('_', 'T', 1) -
92% success
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
Dead Ends
Common approaches that don't work:
-
60% fail
strptime works but bypasses Pydantic validation, so type errors surface later as AttributeError.
-
75% fail
Loses timezone-aware comparison and arithmetic capabilities.