normalize_datetime#

safir.pydantic.normalize_datetime(v)#

Pydantic validator for datetime fields.

Supports datetime fields given in either any format supported by Pydantic natively, or in seconds since epoch (which Pydantic doesn’t support). This validator ensures that datetimes are always stored in the model as timezone-aware UTC datetimes.

Parameters:

v (UnionType[int, datetime, None]) – The field representing a datetime.

Returns:

The timezone-aware datetime or None if the input was None.

Return type:

datetime.datetime or None

Examples

Here is a partial model that uses this function as a validator.

class Info(BaseModel):
    last_used: Optional[datetime] = Field(
        None,
        title="Last used",
        description="When last used in seconds since epoch",
        example=1614986130,
    )

    _normalize_last_used = validator(
        "last_used", allow_reuse=True, pre=True
    )(normalize_datetime)