Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pydantic preprocessing field value

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?

like image 668
Elgin Cahangirov Avatar asked Jun 28 '26 22:06

Elgin Cahangirov


1 Answers

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)]
like image 125
lig Avatar answered Jul 01 '26 20:07

lig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!