fix(cost): evaluate off-peak windows in UTC for timezone-aware inputs

_is_within_off_peak_window used current_time.time(), which drops tzinfo, so a caller passing a non-UTC aware datetime had the window compared against local wall-clock instead of UTC. That silently mispriced off-peak requests. Normalize aware datetimes to UTC before comparing; naive datetimes stay as-is per the documented UTC contract. Added a regression test with a UTC+8 datetime that fails without the fix
This commit is contained in:
Srivatsa03 2026-08-02 21:34:09 -05:00
parent 9fc77f1222
commit f2c663515c
2 changed files with 15 additions and 0 deletions

View file

@ -300,6 +300,8 @@ def _is_within_off_peak_window(off_peak_hours_utc: str | list[str], current_time
"""
if current_time is None:
current_time = datetime.now(timezone.utc)
elif current_time.tzinfo is not None:
current_time = current_time.astimezone(timezone.utc)
now = current_time.time()
windows = [off_peak_hours_utc] if isinstance(off_peak_hours_utc, str) else off_peak_hours_utc
for window in windows:

View file

@ -3983,6 +3983,19 @@ def test_is_within_off_peak_window_multiple_windows():
assert _is_within_off_peak_window([], datetime(2026, 1, 1, 14, 0, tzinfo=timezone.utc)) is False
def test_is_within_off_peak_window_normalizes_timezone_aware_input():
from datetime import datetime, timedelta, timezone
# A caller may pass a non-UTC aware datetime; the window is UTC and must be
# evaluated in UTC, not against the caller's wall-clock. 09:00 at UTC+8 is
# 01:00 UTC, inside the 01:00-05:00 window.
tz_plus_8 = timezone(timedelta(hours=8))
assert _is_within_off_peak_window("01:00-05:00", datetime(2026, 1, 1, 9, 0, tzinfo=tz_plus_8)) is True
assert _is_within_off_peak_window("01:00-05:00", datetime(2026, 1, 1, 12, 0, tzinfo=tz_plus_8)) is True
# 06:00 at UTC+8 is 22:00 UTC the previous day, outside the window
assert _is_within_off_peak_window("01:00-05:00", datetime(2026, 1, 1, 6, 0, tzinfo=tz_plus_8)) is False
def test_is_within_off_peak_window_malformed_returns_false():
from datetime import datetime, timezone