Skip to Content
Binal
Advanced

Custom Codecs

Separate Python and binary representations

from datetime import datetime, timezone
from typing import Annotated

from binal import BinaryModel, Codec, UInt32, UInt64


class TimestampCodec(Codec[datetime, int]):
    storage = UInt64

    def encode(self, value: datetime) -> int:
        return int(value.timestamp())

    def decode(self, value: int) -> datetime:
        return datetime.fromtimestamp(value, tz=timezone.utc)


Timestamp = Annotated[datetime, TimestampCodec()]


class Event(BinaryModel, byte_order="big"):
    id: UInt32
    timestamp: Timestamp