diff --git a/pydantic_extra_types/epoch.py b/pydantic_extra_types/epoch.py index 2092cb2..c9dda44 100644 --- a/pydantic_extra_types/epoch.py +++ b/pydantic_extra_types/epoch.py @@ -43,6 +43,22 @@ def _f(cls, value: Any, serializer: Callable[[Any], Any]) -> Any: # pragma: no class Number(_Base): + """epoch.Number parses unix timestamp as float and converts it to datetime. + + ```py + from pydantic import BaseModel + + from pydantic_extra_types import epoch + + class LogEntry(BaseModel): + timestamp: epoch.Number + + logentry = LogEntry(timestamp=1.1) + print(logentry) + #> timestamp=datetime.datetime(1970, 1, 1, 0, 0, 1, 100000, tzinfo=datetime.timezone.utc) + ``` + """ + TYPE = 'number' SCHEMA = core_schema.float_schema() @@ -53,6 +69,23 @@ def _f(cls, value: Any, serializer: Callable[[float], float]) -> float: class Integer(_Base): + """epoch.Integer parses unix timestamp as integer and converts it to datetime. + + ``` + ```py + from pydantic import BaseModel + + from pydantic_extra_types import epoch + + class LogEntry(BaseModel): + timestamp: epoch.Integer + + logentry = LogEntry(timestamp=1) + print(logentry) + #> timestamp=datetime.datetime(1970, 1, 1, 0, 0, 1, tzinfo=datetime.timezone.utc) + ``` + """ + TYPE = 'integer' SCHEMA = core_schema.int_schema() diff --git a/tests/test_json_schema.py b/tests/test_json_schema.py index 0580279..6b55bbf 100644 --- a/tests/test_json_schema.py +++ b/tests/test_json_schema.py @@ -11,6 +11,7 @@ from typing_extensions import Annotated import pydantic_extra_types +from pydantic_extra_types import epoch from pydantic_extra_types.color import Color from pydantic_extra_types.coordinate import Coordinate, Latitude, Longitude from pydantic_extra_types.country import CountryAlpha2, CountryAlpha3, CountryNumericCode, CountryShortName @@ -464,6 +465,41 @@ ], }, ), + ( + epoch.Integer, + { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'x': { + 'title': 'X', + 'type': 'integer', + 'format': 'date-time', + }, + }, + 'required': [ + 'x', + ], + } + ), + ( + epoch.Number, + { + 'title': 'Model', + 'type': 'object', + 'properties': { + 'x': { + 'title': 'X', + 'type': 'number', + 'format': 'date-time', + }, + }, + 'required': [ + 'x', + ], + } + ) + ], ) def test_json_schema(cls, expected):