Skip to content

Commit 390b303

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

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

src/frequenz/client/electricity_trading/_client.py

Lines changed: 27 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,29 @@ 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+
return Timestamp().FromDatetime(dt.astimezone(ZoneInfo("UTC")))
10091030

10101031
public_order_filter = PublicOrderBookFilter(
10111032
delivery_period=delivery_period,
@@ -1025,12 +1046,12 @@ def dt_to_pb_timestamp(dt: datetime) -> Timestamp:
10251046
electricity_trading_pb2.ReceivePublicOrderBookStreamRequest(
10261047
filter=public_order_filter.to_pb(),
10271048
start_time=(
1028-
dt_to_pb_timestamp(start_time)
1049+
dt_to_pb_timestamp_utc(start_time)
10291050
if start_time
10301051
else None
10311052
),
10321053
end_time=(
1033-
dt_to_pb_timestamp(end_time) if end_time else None
1054+
dt_to_pb_timestamp_utc(end_time) if end_time else None
10341055
),
10351056
),
10361057
metadata=self._metadata,

0 commit comments

Comments
 (0)