Closed ameyarao98 closed 3 months ago
I have been using this w/ Pydantic V2:
def iso_format(dt: datetime) -> str:
return dt.isoformat()
UTCTimestamp = Annotated[
datetime,
PlainSerializer(iso_format, return_type=str),
]
You can add a PlainValidator
for help in converting to the proper iso string
Edit: You might also have to add WithJsonSchema
to the annotation to get it to work well with OpenAPI schema generation
The current implementation is a bit hacky, and would not work with pydantic v2. It could be made into a
datetime
object, which Pydantic can parse from various formats,making it easier to create a message if not using a string. There should still however be a manual check when parsed from a string that it fits the ISO standard. Some custom logic (or someting in dateutil?) may be needed to turn the datetime into the proper format