| 
 | 1 | +from __future__ import annotations  | 
 | 2 | + | 
 | 3 | +import datetime  | 
 | 4 | +from typing import Any, Callable  | 
 | 5 | + | 
 | 6 | +import pydantic_core.core_schema  | 
 | 7 | +from pydantic import GetJsonSchemaHandler  | 
 | 8 | +from pydantic.json_schema import JsonSchemaValue  | 
 | 9 | +from pydantic_core import CoreSchema, core_schema  | 
 | 10 | + | 
 | 11 | +EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)  | 
 | 12 | + | 
 | 13 | + | 
 | 14 | +class _Base(datetime.datetime):  | 
 | 15 | +    TYPE: str = ""  | 
 | 16 | +    SCHEMA: pydantic_core.core_schema.CoreSchema  | 
 | 17 | + | 
 | 18 | +    @classmethod  | 
 | 19 | +    def __get_pydantic_json_schema__(  | 
 | 20 | +        cls, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler  | 
 | 21 | +    ) -> JsonSchemaValue:  | 
 | 22 | +        field_schema: dict[str, Any] = {}  | 
 | 23 | +        field_schema.update(type=cls.TYPE, format="date-time")  | 
 | 24 | +        return field_schema  | 
 | 25 | + | 
 | 26 | +    @classmethod  | 
 | 27 | +    def __get_pydantic_core_schema__(  | 
 | 28 | +        cls, source: type[Any], handler: Callable[[Any], CoreSchema]  | 
 | 29 | +    ) -> core_schema.CoreSchema:  | 
 | 30 | +        return core_schema.with_info_after_validator_function(  | 
 | 31 | +            cls._validate,  | 
 | 32 | +            cls.SCHEMA,  | 
 | 33 | +            serialization=core_schema.wrap_serializer_function_ser_schema(cls._f, return_schema=cls.SCHEMA),  | 
 | 34 | +        )  | 
 | 35 | + | 
 | 36 | +    @classmethod  | 
 | 37 | +    def _validate(cls, __input_value: Any, _: Any) -> datetime.datetime:  | 
 | 38 | +        return EPOCH + datetime.timedelta(seconds=__input_value)  | 
 | 39 | + | 
 | 40 | +    @classmethod  | 
 | 41 | +    def _f(cls, value: Any, serializer: Callable[[Any], Any]) -> Any:  # pragma: no cover  | 
 | 42 | +        raise NotImplementedError(cls)  | 
 | 43 | + | 
 | 44 | + | 
 | 45 | +class Number(_Base):  | 
 | 46 | +    TYPE = "number"  | 
 | 47 | +    SCHEMA = core_schema.float_schema()  | 
 | 48 | + | 
 | 49 | +    @classmethod  | 
 | 50 | +    def _f(cls, value: Any, serializer: Callable[[float], float]) -> float:  | 
 | 51 | +        ts = value.timestamp()  | 
 | 52 | +        return serializer(ts)  | 
 | 53 | + | 
 | 54 | + | 
 | 55 | +class Integer(_Base):  | 
 | 56 | +    TYPE = "integer"  | 
 | 57 | +    SCHEMA = core_schema.int_schema()  | 
 | 58 | + | 
 | 59 | +    @classmethod  | 
 | 60 | +    def _f(cls, value: Any, serializer: Callable[[int], int]) -> int:  | 
 | 61 | +        ts = value.timestamp()  | 
 | 62 | +        return serializer(int(ts))  | 
0 commit comments