I have data in which dates are represented as ISO strings. Example:
{"name": "John", "last_active": "2021-10-13T17:16:49-04:00"}
My Pydantic model:
from datetime import datetime
from pydantic import BaseModel
class User(BaseModel):
name: str
last_active: datetime
I want to achieve automatic date conversion when I do: User(**data). Pydantic actually parses datetime object from ISO string automatically, but I also need to convert these dates to UTC timezone, like:
datetime.datetime.fromisoformat(iso_str).replace(
tzinfo=datetime.timezone.utc
)
What is the clean way of doing this with pydantic? More generally, do pydantic provide hook for preprocessing the passed data?
What you are looking for is validators. Here is the documentation for Pydantic Field Validators.
It's possible to write a validator that uses mode='before' for validating value before passing it to the model constructor.
from datetime import datetime
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
last_active: datetime
@field_validator('last_active', mode='before')
def force_utc(cls, value: datetime) -> datetime:
return datetime.fromisoformat(iso_str).replace(tzinfo=datetime.timezone.utc)
It's also possible to use typing.Annotated for defining validators.
from datetime import datetime
from typing import Annotated
from pydantic import BaseModel, BeforeValidator
def force_utc(cls, value: datetime) -> datetime:
return datetime.fromisoformat(iso_str).replace(tzinfo=datetime.timezone.utc)
class User(BaseModel):
name: str
last_active: Annotated[datetime, BeforeValidator(force_utc)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With