Skip to content

Commit 0e7c87c

Browse files
committed
Add from_timedelta as a constructor for DeliveryDuration
Signed-off-by: Sahas Subramanian <[email protected]>
1 parent 661792d commit 0e7c87c

File tree

1 file changed

+28
-0
lines changed
  • src/frequenz/client/electricity_trading

1 file changed

+28
-0
lines changed

src/frequenz/client/electricity_trading/_types.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,34 @@ class DeliveryDuration(enum.Enum):
312312
MINUTES_60 = delivery_duration_pb2.DeliveryDuration.DELIVERY_DURATION_60
313313
"""1-hour contract duration."""
314314

315+
@classmethod
316+
def from_timedelta(cls, duration: timedelta) -> Self:
317+
"""Convert a timedelta to a DeliveryDuration enum.
318+
319+
Args:
320+
duration: The duration as a timedelta.
321+
322+
Returns:
323+
The corresponding DeliveryDuration enum value.
324+
325+
Raises:
326+
ValueError: If the duration is not one of the supported values.
327+
"""
328+
minutes = duration.total_seconds() / 60
329+
match minutes:
330+
case 5:
331+
return DeliveryDuration.MINUTES_5
332+
case 15:
333+
return DeliveryDuration.MINUTES_15
334+
case 30:
335+
return DeliveryDuration.MINUTES_30
336+
case 60:
337+
return DeliveryDuration.MINUTES_60
338+
case _:
339+
raise ValueError(
340+
"Invalid duration value. Duration must be 5, 15, 30, or 60 minutes."
341+
)
342+
315343
@classmethod
316344
@from_pb
317345
def from_pb(

0 commit comments

Comments
 (0)