Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

data type for unix timestamp - Epoch #238

Closed
4 of 13 tasks
commonism opened this issue Nov 14, 2024 · 0 comments · Fixed by #240
Closed
4 of 13 tasks

data type for unix timestamp - Epoch #238

commonism opened this issue Nov 14, 2024 · 0 comments · Fixed by #240

Comments

@commonism
Copy link
Contributor

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

Description

Current pydantic supports datetime.datetime type, serialization as {type: string, format: date-time}.
De-serialisation of this type includes coercion from integer in ms or seconds since epoch as well.
Serialization is limited to iso-format as string.

I propose to create a new type, Epoch {type: integer, format: date-time} to be used for unix timestamps which gets serialized to integer and has proper semantics for the schema.

I currently use an Annotated datetime, the schema generated does not match the value, it's ugly, incomplete and carrying this to multiple projects is building tomorrows technical debt.

Having Epoch as a standard data type would improve usability for pydantic at a minimal cost.

import datetime
from typing import Any

from typing_extensions import Annotated

from pydantic import BaseModel, SerializerFunctionWrapHandler
from pydantic.functional_serializers import WrapSerializer


def ser_wrap(v: Any, nxt: SerializerFunctionWrapHandler) -> int:
    return int(v.timestamp())

Epoch = Annotated[datetime.datetime, WrapSerializer(ser_wrap, when_used='json'), ]


class A(BaseModel):
    epoch: Epoch

now = datetime.datetime.now()
ts = int(now.timestamp())
a = A.model_validate({"epoch":now.timestamp()})
v = a.model_dump(mode='json')
assert v["epoch"] == ts

b = A.model_construct(epoch=now)
v = b.model_dump(mode='json')
assert v["epoch"] == ts

c = A.model_validate(dict(epoch=now))
v = c.model_dump(mode='json')
assert v["epoch"] == ts

Affected Components

@Viicos Viicos transferred this issue from pydantic/pydantic Nov 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant