mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
fix: render datetime model keys in their timezone, not the host's
Additional changes - A series created from pandas takes the timezone of its index, like a data frame. - Row methods of a data frame find their rows when `tz` differs from the host timezone. - to_timezone(date_time=...) names the timezone of an aware date-time, or the Etc/GMT zone of its UTC offset. - to_timezone(utc_offset=...) raises for offsets without an Etc/GMT zone instead of returning an invalid name. - Group the to_timezone tests in TestToTimezone. Closes #1592 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
+64
-16
@@ -11,6 +11,7 @@ from typing import Any, cast
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import babel
|
||||
import pandas as pd
|
||||
import pendulum
|
||||
import pytest
|
||||
from pendulum.tz.timezone import Timezone
|
||||
@@ -1556,26 +1557,73 @@ class TestToDuration:
|
||||
# -----------------------------
|
||||
|
||||
|
||||
def test_to_timezone_string():
|
||||
"""Test to_timezone function returns correct timezone as a string."""
|
||||
location = (40.7128, -74.0060) # New York City coordinates
|
||||
result = to_timezone(location=location, as_string=True)
|
||||
assert result == "America/New_York", "Expected timezone string 'America/New_York'"
|
||||
class TestToTimezone:
|
||||
def test_to_timezone_string(self):
|
||||
"""Test to_timezone function returns correct timezone as a string."""
|
||||
location = (40.7128, -74.0060) # New York City coordinates
|
||||
result = to_timezone(location=location, as_string=True)
|
||||
assert result == "America/New_York", "Expected timezone string 'America/New_York'"
|
||||
|
||||
|
||||
def test_to_timezone_timezone():
|
||||
"""Test to_timezone function returns correct timezone as a Timezone object."""
|
||||
location = (40.7128, -74.0060) # New York City coordinates
|
||||
result = to_timezone(location=location)
|
||||
assert isinstance(result, Timezone), "Expected a Timezone object"
|
||||
assert result.name == "America/New_York", "Expected Timezone name 'America/New_York'"
|
||||
def test_to_timezone_timezone(self):
|
||||
"""Test to_timezone function returns correct timezone as a Timezone object."""
|
||||
location = (40.7128, -74.0060) # New York City coordinates
|
||||
result = to_timezone(location=location)
|
||||
assert isinstance(result, Timezone), "Expected a Timezone object"
|
||||
assert result.name == "America/New_York", "Expected Timezone name 'America/New_York'"
|
||||
|
||||
|
||||
def test_to_timezone_invalid_coordinates():
|
||||
"""Test to_timezone function handles invalid coordinates gracefully."""
|
||||
location = (100.0, 200.0) # Invalid coordinates outside Earth range
|
||||
with pytest.raises(ValueError, match="Invalid latitude/longitude"):
|
||||
to_timezone(location=location, as_string=True)
|
||||
def test_to_timezone_invalid_coordinates(self):
|
||||
"""Test to_timezone function handles invalid coordinates gracefully."""
|
||||
location = (100.0, 200.0) # Invalid coordinates outside Earth range
|
||||
with pytest.raises(ValueError, match="Invalid latitude/longitude"):
|
||||
to_timezone(location=location, as_string=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"utc_offset, expected",
|
||||
[(0, "UTC"), (2, "Etc/GMT-2"), (-3, "Etc/GMT+3"), (14, "Etc/GMT-14"), (-12, "Etc/GMT+12")],
|
||||
)
|
||||
def test_to_timezone_utc_offset(self, utc_offset, expected):
|
||||
"""A whole-hour UTC offset gives its Etc/GMT zone (inverted sign), usable as a timezone."""
|
||||
assert to_timezone(utc_offset=utc_offset, as_string=True) == expected
|
||||
assert to_timezone(utc_offset=utc_offset, as_string=False).name == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("utc_offset", [5.5, -3.5, -13, 15])
|
||||
def test_to_timezone_utc_offset_without_zone(self, utc_offset):
|
||||
"""An offset without an Etc/GMT zone raises instead of returning an invalid name."""
|
||||
with pytest.raises(ValueError, match="No timezone for UTC offset"):
|
||||
to_timezone(utc_offset=utc_offset, as_string=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"date_time, expected",
|
||||
[
|
||||
(pd.Timestamp("2026-09-16T10:00:00", tz="Europe/Berlin"), "Europe/Berlin"),
|
||||
(to_datetime("2026-09-16T10:00:00", in_timezone="Asia/Tokyo"), "Asia/Tokyo"),
|
||||
(pd.Timestamp("2026-09-16T08:00:00", tz="Etc/UTC"), "UTC"),
|
||||
# pandas names a fixed offset "UTC-03:00": the Etc/GMT zone of the offset.
|
||||
(pd.Timestamp("2026-09-16T05:00:00-03:00"), "Etc/GMT+3"),
|
||||
],
|
||||
)
|
||||
def test_to_timezone_date_time(self, date_time, expected):
|
||||
"""The timezone of a date-time is its named zone, else the Etc/GMT zone of its offset."""
|
||||
assert to_timezone(date_time=date_time, as_string=True) == expected
|
||||
assert to_timezone(date_time=date_time, as_string=False).name == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"date_time, match",
|
||||
[
|
||||
(pd.Timestamp("2026-09-16T08:00:00"), "without timezone"),
|
||||
(pd.Timestamp("2026-09-16T13:30:00+05:30"), "No timezone for UTC offset"),
|
||||
],
|
||||
)
|
||||
def test_to_timezone_date_time_without_zone(self, date_time, match):
|
||||
"""A naive date-time or an offset without an Etc/GMT zone raises."""
|
||||
with pytest.raises(ValueError, match=match):
|
||||
to_timezone(date_time=date_time, as_string=True)
|
||||
|
||||
|
||||
# -----------------------------
|
||||
|
||||
@@ -15,6 +15,13 @@ from akkudoktoreos.core.pydantic import (
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import DateTime, compare_datetimes, to_datetime
|
||||
|
||||
# Host timezones the index rendering must not depend on (#1592).
|
||||
HOST_TIMEZONES = ["UTC", "Europe/Berlin", "America/New_York"]
|
||||
# 08:00 UTC: 10:00 in Berlin (summer time), 17:00 in Tokyo.
|
||||
UTC_START = "2026-09-16T08:00:00+00:00"
|
||||
# The same instant with a fixed offset, as pandas reads it from a string.
|
||||
OFFSET_START = "2026-09-16T05:00:00-03:00"
|
||||
|
||||
|
||||
class PydanticTestModel(PydanticBaseModel):
|
||||
"""Minimal test model for exercising PydanticBaseModel helpers."""
|
||||
@@ -584,6 +591,92 @@ class TestPydanticDateTimeDataFrame:
|
||||
assert "extra" not in model.data[key]
|
||||
assert "extra" not in model.dtypes
|
||||
|
||||
@pytest.mark.parametrize("host_timezone", HOST_TIMEZONES)
|
||||
def test_index_follows_requested_tz(self, set_other_timezone, host_timezone):
|
||||
"""The index is rendered in the requested ``tz``, whatever the host timezone (#1592)."""
|
||||
set_other_timezone(host_timezone)
|
||||
df = pd.DataFrame({"value": [1.0, 2.0]}, index=pd.date_range(UTC_START, periods=2, freq="h"))
|
||||
|
||||
model = PydanticDateTimeDataFrame.from_dataframe(df, tz="Asia/Tokyo")
|
||||
|
||||
assert model.tz == "Asia/Tokyo"
|
||||
assert list(model.data) == ["2026-09-16T17:00:00+09:00", "2026-09-16T18:00:00+09:00"]
|
||||
|
||||
@pytest.mark.parametrize("host_timezone", HOST_TIMEZONES)
|
||||
def test_index_follows_data_tz(self, set_other_timezone, host_timezone):
|
||||
"""Without ``tz`` the index keeps the timezone of the data, not the host's (#1592)."""
|
||||
set_other_timezone(host_timezone)
|
||||
index = pd.date_range(UTC_START, periods=2, freq="h").tz_convert("Europe/Berlin")
|
||||
df = pd.DataFrame({"value": [1.0, 2.0]}, index=index)
|
||||
|
||||
model = PydanticDateTimeDataFrame.from_dataframe(df)
|
||||
|
||||
assert model.tz == "Europe/Berlin"
|
||||
assert list(model.data) == ["2026-09-16T10:00:00+02:00", "2026-09-16T11:00:00+02:00"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tz, expected_key",
|
||||
[
|
||||
("Europe/Berlin", "2026-09-16T10:00:00+02:00"),
|
||||
(None, "2026-09-16T08:00:00Z"),
|
||||
],
|
||||
)
|
||||
def test_validation_renders_index_in_tz(self, set_other_timezone, tz, expected_key):
|
||||
"""Validated input (e.g. a request body) is rendered in ``tz``, in UTC without one."""
|
||||
set_other_timezone("America/New_York")
|
||||
|
||||
model = PydanticDateTimeDataFrame.model_validate(
|
||||
{"data": {"2026-09-16T08:00:00+00:00": {"value": 1.0}}, "tz": tz}
|
||||
)
|
||||
|
||||
assert list(model.data) == [expected_key]
|
||||
assert PydanticDateTimeDataFrame.model_validate_json(model.model_dump_json()).model_dump() == model.model_dump()
|
||||
|
||||
def test_row_access_with_tz_other_than_host(self, set_other_timezone):
|
||||
"""Row methods find the rows of a frame whose ``tz`` differs from the host timezone."""
|
||||
set_other_timezone("America/New_York")
|
||||
df = pd.DataFrame({"value": [1.0, 2.0]}, index=pd.date_range(UTC_START, periods=2, freq="h"))
|
||||
model = PydanticDateTimeDataFrame.from_dataframe(df, tz="Europe/Berlin")
|
||||
|
||||
model.update_row(to_datetime(UTC_START), {"value": 9.0})
|
||||
|
||||
assert model.get_value("2026-09-16T10:00:00+02:00", "value") == 9.0
|
||||
|
||||
def test_tz_change_and_round_trip(self, set_other_timezone):
|
||||
"""Assigning ``tz`` re-renders the index; ``to_dataframe`` keeps the instants."""
|
||||
set_other_timezone("America/New_York")
|
||||
df = pd.DataFrame({"value": [1.0, 2.0]}, index=pd.date_range(UTC_START, periods=2, freq="h"))
|
||||
model = PydanticDateTimeDataFrame.from_dataframe(df, tz="Europe/Berlin")
|
||||
|
||||
model.tz = "Asia/Tokyo"
|
||||
|
||||
assert list(model.data) == ["2026-09-16T17:00:00+09:00", "2026-09-16T18:00:00+09:00"]
|
||||
result = model.to_dataframe()
|
||||
for result_dt, expected_dt in zip(result.index, df.index):
|
||||
assert compare_datetimes(to_datetime(result_dt), to_datetime(expected_dt)).equal
|
||||
|
||||
def test_offset_index_gets_a_valid_tz(self, set_other_timezone):
|
||||
"""A fixed-offset index (pandas names it ``UTC-03:00``) gets its ``Etc/GMT`` zone."""
|
||||
set_other_timezone("Europe/Berlin")
|
||||
df = pd.DataFrame({"value": [1.0]}, index=pd.to_datetime([OFFSET_START]))
|
||||
|
||||
model = PydanticDateTimeDataFrame.from_dataframe(df)
|
||||
|
||||
assert model.tz == "Etc/GMT+3"
|
||||
assert list(model.data) == [OFFSET_START]
|
||||
|
||||
def test_offset_column_gets_a_valid_tz(self, set_other_timezone):
|
||||
"""Without a timezone-aware index, a fixed-offset datetime column names the zone."""
|
||||
set_other_timezone("Europe/Berlin")
|
||||
df = pd.DataFrame(
|
||||
{"value": [1.0], "date_time": pd.to_datetime([OFFSET_START])},
|
||||
index=pd.to_datetime(["2026-09-16T08:00:00"]),
|
||||
)
|
||||
|
||||
model = PydanticDateTimeDataFrame.from_dataframe(df)
|
||||
|
||||
assert model.tz == "Etc/GMT+3"
|
||||
|
||||
|
||||
class TestPydanticDateTimeSeries:
|
||||
def test_valid_series(self):
|
||||
@@ -597,3 +690,87 @@ class TestPydanticDateTimeSeries:
|
||||
expected_dt = to_datetime(dt)
|
||||
result_dt = to_datetime(result.index[i])
|
||||
assert compare_datetimes(result_dt, expected_dt).equal
|
||||
|
||||
@pytest.mark.parametrize("host_timezone", HOST_TIMEZONES)
|
||||
def test_index_follows_series_tz(self, set_other_timezone, host_timezone):
|
||||
"""A timezone-aware series keeps its timezone, not the host's (#1592)."""
|
||||
set_other_timezone(host_timezone)
|
||||
index = pd.date_range(UTC_START, periods=2, freq="h").tz_convert("Europe/Berlin")
|
||||
|
||||
model = PydanticDateTimeSeries.from_series(pd.Series([1.0, 2.0], index=index))
|
||||
|
||||
assert model.tz == "Europe/Berlin"
|
||||
assert list(model.data) == ["2026-09-16T10:00:00+02:00", "2026-09-16T11:00:00+02:00"]
|
||||
|
||||
@pytest.mark.parametrize("host_timezone", HOST_TIMEZONES)
|
||||
def test_index_follows_requested_tz(self, set_other_timezone, host_timezone):
|
||||
"""The index is rendered in the requested ``tz``, whatever the host timezone (#1592)."""
|
||||
set_other_timezone(host_timezone)
|
||||
series = pd.Series([1.0, 2.0], index=pd.date_range(UTC_START, periods=2, freq="h"))
|
||||
|
||||
model = PydanticDateTimeSeries.from_series(series, tz="Asia/Tokyo")
|
||||
|
||||
assert model.tz == "Asia/Tokyo"
|
||||
assert list(model.data) == ["2026-09-16T17:00:00+09:00", "2026-09-16T18:00:00+09:00"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"start, expected_tz, expected_key",
|
||||
[
|
||||
(OFFSET_START, "Etc/GMT+3", OFFSET_START),
|
||||
# No Etc/GMT zone for half hours: UTC, same instant.
|
||||
("2026-09-16T13:30:00+05:30", "UTC", "2026-09-16T08:00:00Z"),
|
||||
],
|
||||
)
|
||||
def test_offset_index_gets_a_valid_tz(
|
||||
self, set_other_timezone, start, expected_tz, expected_key
|
||||
):
|
||||
"""A fixed-offset index (pandas names it e.g. ``UTC-03:00``) gets a zone ``tz`` accepts."""
|
||||
set_other_timezone("Europe/Berlin")
|
||||
|
||||
model = PydanticDateTimeSeries.from_series(pd.Series([1.0], index=pd.to_datetime([start])))
|
||||
|
||||
assert model.tz == expected_tz
|
||||
assert list(model.data) == [expected_key]
|
||||
|
||||
def test_tz_change_and_round_trip(self, set_other_timezone):
|
||||
"""Assigning ``tz`` re-renders the index; ``to_series`` keeps the instants."""
|
||||
set_other_timezone("America/New_York")
|
||||
series = pd.Series([1.0, 2.0], index=pd.date_range(UTC_START, periods=2, freq="h"))
|
||||
model = PydanticDateTimeSeries.from_series(series.copy(), tz="Europe/Berlin")
|
||||
|
||||
model.tz = "Asia/Tokyo"
|
||||
|
||||
assert list(model.data) == ["2026-09-16T17:00:00+09:00", "2026-09-16T18:00:00+09:00"]
|
||||
result = model.to_series()
|
||||
for result_dt, expected_dt in zip(result.index, series.index):
|
||||
assert compare_datetimes(to_datetime(result_dt), to_datetime(expected_dt)).equal
|
||||
|
||||
def test_naive_series_uses_host_timezone(self, set_other_timezone):
|
||||
"""A naive index has no timezone of its own: ``tz`` and the keys use the host's."""
|
||||
host_timezone = set_other_timezone("Asia/Singapore")
|
||||
timestamp = pd.Timestamp("2026-09-16T16:00:00")
|
||||
|
||||
model = PydanticDateTimeSeries.from_series(pd.Series([1.0], index=[timestamp]))
|
||||
|
||||
assert model.tz == host_timezone
|
||||
(key,) = model.data
|
||||
assert key.endswith("+08:00")
|
||||
assert compare_datetimes(to_datetime(key), to_datetime(timestamp)).equal
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tz, expected_key",
|
||||
[
|
||||
("Europe/Berlin", "2026-09-16T10:00:00+02:00"),
|
||||
(None, "2026-09-16T08:00:00Z"),
|
||||
],
|
||||
)
|
||||
def test_validation_renders_index_in_tz(self, set_other_timezone, tz, expected_key):
|
||||
"""Validated input (e.g. a request body) is rendered in ``tz``, in UTC without one."""
|
||||
set_other_timezone("America/New_York")
|
||||
|
||||
model = PydanticDateTimeSeries.model_validate(
|
||||
{"data": {"2026-09-16T08:00:00+00:00": 1.0}, "tz": tz}
|
||||
)
|
||||
|
||||
assert list(model.data) == [expected_key]
|
||||
assert PydanticDateTimeSeries.model_validate_json(model.model_dump_json()).model_dump() == model.model_dump()
|
||||
|
||||
Reference in New Issue
Block a user