1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
import os
import time
from dataclasses import dataclass
from datetime import datetime
from apischema import serialize
# Set UTC timezone for example
os.environ["TZ"] = "UTC"
time.tzset()
def to_timestamp(d: datetime) -> int:
return int(d.timestamp())
@dataclass
class Foo:
bar: datetime
# timestamp conversion is not applied on Foo field because it's discarded
# when encountering Foo
assert serialize(Foo, Foo(datetime(2019, 10, 13)), conversion=to_timestamp) == {
"bar": "2019-10-13T00:00:00"
}
# timestamp conversion is applied on every member of list
assert serialize(list[datetime], [datetime(1970, 1, 1)], conversion=to_timestamp) == [0]
|