|
| 1 | +import datetime |
| 2 | +from typing import Any, Callable |
| 3 | + |
| 4 | +from pydantic import GetJsonSchemaHandler |
| 5 | +from pydantic.json_schema import JsonSchemaValue |
| 6 | +from pydantic_core import CoreSchema, core_schema |
| 7 | + |
| 8 | +EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc) |
| 9 | + |
| 10 | + |
| 11 | +class Epoch(datetime.datetime): |
| 12 | + @classmethod |
| 13 | + def __get_pydantic_json_schema__( |
| 14 | + cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler |
| 15 | + ) -> JsonSchemaValue: |
| 16 | + field_schema: dict[str, Any] = {} |
| 17 | + field_schema.update(type='number', format='date-time') |
| 18 | + return field_schema |
| 19 | + |
| 20 | + @classmethod |
| 21 | + def __get_pydantic_core_schema__( |
| 22 | + cls, source: type[Any], handler: Callable[[Any], CoreSchema] |
| 23 | + ) -> core_schema.CoreSchema: |
| 24 | + def f(value, serializer): |
| 25 | + return serializer(value.timestamp()) |
| 26 | + return core_schema.with_info_after_validator_function( |
| 27 | + cls._validate, core_schema.float_schema(), |
| 28 | + serialization=core_schema.wrap_serializer_function_ser_schema(f, return_schema=core_schema.float_schema()) |
| 29 | + ) |
| 30 | + |
| 31 | + @classmethod |
| 32 | + def _validate(cls, __input_value: Any, _: Any) -> "Epoch": |
| 33 | + return EPOCH + datetime.timedelta(seconds=__input_value) |
| 34 | + |
| 35 | + |
0 commit comments