normalize_isodatetime

safir.pydantic.normalize_isodatetime(v)

Pydantic field validator for datetime fields in ISO format.

This field validator requires the ISO 8601 date and time format with Z as the time zone (YYYY-MM-DDTHH:MM:SSZ). This format is compatible with Kubernetes and the ISO UWS standard and is the same format produced by safir.datetime.isodatetime. It should be used when the ambiguous formats supported by Pydantic by default (such as dates and times without time zone information) shouldn’t be allowed.

Parameters:

v (str | 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 field validator.

class Info(BaseModel):
    last_used: datetime | None = Field(
        None,
        title="Last used",
        description="Date and time last used",
        examples=["2023-01-25T15:44:34Z"],
    )

    _normalize_last_used = field_validator("last_used", mode="before")(
        normalize_isodatetime
    )