Skip to content

conversion

frequenz.client.base.conversion ¤

Helper functions to convert to/from common python types.

Functions¤

frequenz.client.base.conversion.to_datetime ¤

to_datetime(
    ts: Timestamp, tz: timezone = timezone.utc
) -> datetime

Convert a protobuf Timestamp to a datetime.

PARAMETER DESCRIPTION
ts

Timestamp object to convert

TYPE: Timestamp

tz

Timezone to use for the datetime

TYPE: timezone DEFAULT: utc

RETURNS DESCRIPTION
datetime

Timestamp converted to datetime

Source code in frequenz/client/base/conversion.py
def to_datetime(ts: Timestamp, tz: timezone = timezone.utc) -> datetime:
    """Convert a protobuf Timestamp to a datetime.

    Args:
        ts: Timestamp object to convert
        tz: Timezone to use for the datetime

    Returns:
        Timestamp converted to datetime
    """
    # Add microseconds and add nanoseconds converted to microseconds
    microseconds = int(ts.nanos / 1000)
    return datetime.fromtimestamp(ts.seconds + microseconds * 1e-6, tz=tz)

frequenz.client.base.conversion.to_timestamp ¤

to_timestamp(dt: datetime | None) -> Timestamp | None

Convert a datetime to a protobuf Timestamp.

Returns None if dt is None.

PARAMETER DESCRIPTION
dt

datetime object to convert

TYPE: datetime | None

RETURNS DESCRIPTION
Timestamp | None

datetime converted to Timestamp

Source code in frequenz/client/base/conversion.py
def to_timestamp(dt: datetime | None) -> Timestamp | None:
    """Convert a datetime to a protobuf Timestamp.

    Returns None if dt is None.

    Args:
        dt: datetime object to convert

    Returns:
        datetime converted to Timestamp
    """
    if dt is None:
        return None

    ts = Timestamp()
    ts.FromDatetime(dt)
    return ts