Skip to content

Commit 334693f

Browse files
Convert timestamp to UTC
Signed-off-by: Matthias Wende <[email protected]>
1 parent 04f5253 commit 334693f

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

src/frequenz/client/electricity_trading/_client.py

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from datetime import datetime, timedelta, timezone
1313
from decimal import Decimal, InvalidOperation
1414
from typing import Any, AsyncIterator, Awaitable, Callable, cast
15+
from zoneinfo import ZoneInfo
1516

1617
import grpc
1718
from frequenz.api.common.v1.pagination.pagination_params_pb2 import PaginationParams
@@ -53,6 +54,7 @@
5354
UpdateOrder,
5455
)
5556

57+
5658
_logger = logging.getLogger(__name__)
5759

5860

@@ -1002,10 +1004,32 @@ def receive_public_order_book(
10021004
grpc.RpcError: If an error occurs while streaming public orders.
10031005
"""
10041006

1005-
def dt_to_pb_timestamp(dt: datetime) -> Timestamp:
1006-
ts = Timestamp()
1007-
ts.FromDatetime(dt)
1008-
return ts
1007+
def dt_to_pb_timestamp_utc(dt: datetime.datetime) -> Timestamp:
1008+
"""
1009+
Converts a Python datetime object to a UTC Protobuf Timestamp.
1010+
1011+
The input datetime 'dt' MUST be timezone-aware.
1012+
1013+
Args:
1014+
dt: The Python datetime object to convert.
1015+
1016+
Returns:
1017+
A Protobuf Timestamp object representing the time in UTC.
1018+
1019+
Raises:
1020+
TypeError: If dt is not a datetime.datetime object.
1021+
ValueError: If the input datetime object is naive (lacks timezone info).
1022+
"""
1023+
if not isinstance(dt, datetime.datetime):
1024+
raise TypeError("Input must be a datetime.datetime object")
1025+
1026+
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
1027+
raise ValueError("Input datetime object must be timezone-aware.")
1028+
1029+
timestamp = Timestamp()
1030+
timestamp.FromDatetime(dt.astimezone(ZoneInfo("UTC")))
1031+
1032+
return timestampo
10091033

10101034
public_order_filter = PublicOrderBookFilter(
10111035
delivery_period=delivery_period,
@@ -1025,12 +1049,14 @@ def dt_to_pb_timestamp(dt: datetime) -> Timestamp:
10251049
electricity_trading_pb2.ReceivePublicOrderBookStreamRequest(
10261050
filter=public_order_filter.to_pb(),
10271051
start_time=(
1028-
dt_to_pb_timestamp(start_time)
1052+
dt_to_pb_timestamp_utc(start_time)
10291053
if start_time
10301054
else None
10311055
),
10321056
end_time=(
1033-
dt_to_pb_timestamp(end_time) if end_time else None
1057+
dt_to_pb_timestamp_utc(end_time)
1058+
if end_time
1059+
else None
10341060
),
10351061
),
10361062
metadata=self._metadata,

0 commit comments

Comments
 (0)