EventDuration

class safir.metrics.EventDuration

Bases: timedelta

A dataclasses-avroschema-compatible timedelta field that serializes to float seconds.

Note

Models that use fields of this type must be subclasses of EventPayload.

dataclasses-avroschema has no built-in support for timedelta fields (even though Pydantic does), and if you declare one in your event payload model, an exception will be thrown when you try to serialize it. By declaring your field with this type, you’ll be able to use timedeltas, and they will serialze to a float number of seconds.

Examples

from datetime import datetime, timedelta, timezone
from safir.metrics import EventDuration, EventPayload

class MyEvent(EventPayload):
    some_field: str = Field()
    duration: EventDuration = Field()


start_time = datetime.now(timezone.utc)
do_some_stuff()
duration: timedelta = datetime.now(timezone.utc) - start_time

payload = MyEvent(some_field="woohoo", duration=duration)