I am designing a Pydantic model that contains some datetime fields, like so:
from pydantic import BaseModel, Field
from datetime import datetime
class Event(BaseModel):
start_date: datetime = Field(..., description="datetime in format YYYY-mm-ddTHH:MM:SS")
end_date: datetime = Field(..., description="datetime in format YYYY-mm-ddTHH:MM:SS")
Helpfully enough, pydantic accepts string values for datetime fields. So an object like Event(start_date="2024-05-03T12:00:00", end_date="2024-05-03T13:00:00")
will be accepted.
However, type checking tools like Pylance in VScode will show errors when creating such objects using string parameters, as a static type check will conclude that the Event
class cannot be instantiated with strings, but needs datetimes.
Is there a way to indicate to type checkers that both strings and datetimes are accepted?
I considered creating Fields with a str | datetime
typehint, but that approach has the drawback that a consumer has to perform type checks at runtime. It probably also messes with Pydantic’s built-in datetime validation.