'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source