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:
Bobby Noelte
2026-11-24 11:52:08 +01:00
parent 0e0a544371
commit 34c19c3573
5 changed files with 392 additions and 50 deletions
+5
View File
@@ -241,6 +241,11 @@ test procedure. These changes are not yet a tagged release.
renders predictions without provider-specific load statistics, keeps the scroll position after
actions and shows no horizontal scrollbar.
- Dropping root privileges no longer fails on non-Unix systems.
- The date-time keys of data frames and series in API responses and requests (e.g. the
`prediction` and `solution` of an optimization solution, the prediction and measurement series)
follow their `tz`, or UTC without one, instead of the timezone of the EOS host. A series takes
the timezone of its data. The keys name the same instants as before; only their UTC offsets
can differ ([#1592](https://github.com/Akkudoktor-EOS/EOS/issues/1592)).
### Security
+91 -27
View File
@@ -49,6 +49,7 @@ from pydantic import (
ValidationError,
ValidationInfo,
field_validator,
model_validator,
)
from pydantic.fields import ComputedFieldInfo, FieldInfo
@@ -1031,6 +1032,63 @@ class PydanticDateTimeData(RootModel):
return cls(root=data)
def _datetime_index_key(index: Any, tz: Optional[str]) -> str:
"""Render a datetime index key of the datetime models.
The key names the same instant in every host timezone; its offset is the one of ``tz``, or
UTC without one, never the host's (#1592). A naive ``index`` is read as ``to_datetime``
reads it.
Args:
index: A datetime-like value.
tz: Timezone name of the model, or None.
Returns:
str: The ISO 8601 datetime string of ``index`` in ``tz``, in UTC without one.
"""
return to_datetime(index, as_string=True, in_timezone=tz or "UTC")
def _render_index_in_tz(data: Dict[str, Any], tz: Optional[str]) -> None:
"""Render the keys of a datetime model's ``data`` in ``tz``, in place.
In place, as assigning ``data`` would validate the model again.
Args:
data: Mapping of datetime index keys to row or series values.
tz: Timezone name of the model, or None.
"""
rendered = {_datetime_index_key(key, tz): value for key, value in data.items()}
data.clear()
data.update(rendered)
def _pandas_timezone_name(sample: pd.Timestamp) -> str:
"""Name the timezone of timezone-aware pandas data for ``tz`` of the datetime models.
`to_timezone` names the timezone, or the ``Etc/GMT`` zone of a fixed offset such as pandas'
``UTC+02:00``. An offset without such a zone (e.g. +05:30) gets ``UTC``; the keys name the
same instants either way.
Args:
sample: A timezone-aware timestamp of the data.
Returns:
str: A timezone name accepted by ``tz``.
"""
try:
return to_timezone(date_time=sample, as_string=True)
except ValueError:
return "UTC"
def _index_timezone_name(index: pd.Index) -> Optional[str]:
"""Name the timezone of a timezone-aware datetime index, None for any other index."""
if not isinstance(index, pd.DatetimeIndex) or index.tz is None or len(index) == 0:
return None
return _pandas_timezone_name(index[0])
class PydanticDateTimeDataFrame(PydanticBaseModel):
"""Pydantic model for validating pandas DataFrame data with datetime index."""
@@ -1071,12 +1129,10 @@ class PydanticDateTimeDataFrame(PydanticBaseModel):
if not all(set(row.keys()) == columns for row in v.values()):
raise ValueError("All rows must have the same columns")
# Convert index datetime strings
# Convert index datetime strings; `render_index_in_tz` renders them in `tz` afterwards,
# as `tz` is validated after `data`.
try:
d = {
to_datetime(dt, as_string=True, in_timezone=info.data.get("tz")): value
for dt, value in v.items()
}
d = {_datetime_index_key(dt, None): value for dt, value in v.items()}
v = d
except (ValueError, TypeError) as e:
raise ValueError(f"Invalid datetime string in index: {e}")
@@ -1095,6 +1151,12 @@ class PydanticDateTimeDataFrame(PydanticBaseModel):
return v
@model_validator(mode="after")
def render_index_in_tz(self) -> "PydanticDateTimeDataFrame":
"""Render the index keys in ``tz``, once all fields are validated."""
_render_index_in_tz(self.data, self.tz)
return self
@field_validator("dtypes")
@classmethod
def validate_dtypes(cls, v: Dict[str, str], info: ValidationInfo) -> Dict[str, str]:
@@ -1159,15 +1221,16 @@ class PydanticDateTimeDataFrame(PydanticBaseModel):
def _detect_data_tz(cls, df: pd.DataFrame) -> Optional[str]:
"""Detect timezone of pandas data."""
# Index first (strongest signal)
if isinstance(df.index, pd.DatetimeIndex) and df.index.tz is not None:
return str(df.index.tz)
index_tz = _index_timezone_name(df.index)
if index_tz is not None:
return index_tz
# Then datetime columns
for col in df.columns:
if is_datetime64_any_dtype(df[col]):
tz = getattr(df[col].dt, "tz", None)
if tz is not None:
return str(tz)
values = df[col].dropna()
if getattr(df[col].dt, "tz", None) is not None and len(values) > 0:
return _pandas_timezone_name(values.iloc[0])
return None
@@ -1226,7 +1289,7 @@ class PydanticDateTimeDataFrame(PydanticBaseModel):
Returns:
str: Normalized datetime string based on model timezone.
"""
return to_datetime(index, as_string=True, in_timezone=self.tz)
return _datetime_index_key(index, self.tz)
def add_row(self, index: str | DateTime, row: Dict[str, Any]) -> None:
"""Add a new row to the dataset.
@@ -1361,9 +1424,12 @@ class PydanticDateTimeSeries(PydanticBaseModel):
@field_validator("data", mode="after")
@classmethod
def validate_datetime_index(cls, v: Dict[str, Any], info: ValidationInfo) -> Dict[str, Any]:
def validate_datetime_index(cls, v: Dict[str, Any]) -> Dict[str, Any]:
"""Validate that all keys can be parsed as datetime strings.
The keys are rendered in UTC here; `render_index_in_tz` renders them in ``tz``
afterwards, as ``tz`` is validated after ``data``.
Args:
v: Dictionary with datetime string keys and series values.
@@ -1373,18 +1439,8 @@ class PydanticDateTimeSeries(PydanticBaseModel):
Raises:
ValueError: If any key cannot be parsed as a datetime.
"""
tz = info.data.get("tz")
if tz is not None:
try:
ZoneInfo(tz)
except KeyError:
tz = None
try:
# Attempt to parse each key as datetime
d = dict()
for dt_str, value in v.items():
d[to_datetime(dt_str, as_string=True, in_timezone=tz)] = value
return d
return {_datetime_index_key(dt_str, None): value for dt_str, value in v.items()}
except (ValueError, TypeError) as e:
raise ValueError(f"Invalid datetime string in index: {e}")
@@ -1398,6 +1454,12 @@ class PydanticDateTimeSeries(PydanticBaseModel):
raise ValueError(f"Invalid timezone: {v}")
return v
@model_validator(mode="after")
def render_index_in_tz(self) -> "PydanticDateTimeSeries":
"""Render the index keys in ``tz``, once all fields are validated."""
_render_index_in_tz(self.data, self.tz)
return self
def to_series(self) -> pd.Series:
"""Convert the validated model data to a pandas Series.
@@ -1415,6 +1477,8 @@ class PydanticDateTimeSeries(PydanticBaseModel):
Args:
series: The pandas Series with datetime index to convert.
tz: Timezone to render the index in. Defaults to the timezone of a timezone-aware
index, else (naive index) the host-local timezone.
Returns:
A new instance containing the Series data.
@@ -1430,11 +1494,11 @@ class PydanticDateTimeSeries(PydanticBaseModel):
model = PydanticDateTimeSeries.from_series(s)
"""
index = pd.Index([to_datetime(dt, as_string=True, in_timezone=tz) for dt in series.index])
series.index = index
if tz is None and len(series.index) > 0:
tz = _index_timezone_name(series.index) or to_timezone(as_string=True)
if len(index) > 0:
tz = to_datetime(series.index[0]).timezone_name
index = pd.Index([_datetime_index_key(dt, tz) for dt in series.index])
series.index = index
return cls(
data=cast(dict[str, Any], series.to_dict()),
+55 -7
View File
@@ -1388,11 +1388,23 @@ def _canonicalize_tz_name(name: str) -> str:
return _UTC_ALIASES.get(name.lower(), name)
def _is_timezone_name(name: Optional[str]) -> bool:
"""Return whether *name* names a timezone Pendulum (and the IANA database) knows."""
if not isinstance(name, str) or not name:
return False
try:
pendulum.timezone(name)
except (ValueError, KeyError):
return False
return True
@overload
def to_timezone(
utc_offset: Optional[float] = None,
location: Optional[Tuple[float, float]] = None,
as_string: Literal[True] = True,
date_time: Optional[datetime.datetime] = None,
) -> str: ...
@@ -1401,6 +1413,7 @@ def to_timezone(
utc_offset: Optional[float] = None,
location: Optional[Tuple[float, float]] = None,
as_string: Literal[False] | None = None,
date_time: Optional[datetime.datetime] = None,
) -> Timezone: ...
@@ -1408,8 +1421,9 @@ def to_timezone(
utc_offset: Optional[float] = None,
location: Optional[Tuple[float, float]] = None,
as_string: Optional[bool] = False,
date_time: Optional[datetime.datetime] = None,
) -> Union[Timezone, str]:
"""Determines the timezone either by UTC offset, geographic location, or local system timezone.
"""Determines the timezone by UTC offset, geographic location, a date-time, or the local system.
Timezone names that are semantically equivalent to UTC (e.g. ``GMT``, ``Z``,
``Etc/GMT``) are canonicalized to ``"UTC"`` before returning.
@@ -1419,10 +1433,15 @@ def to_timezone(
Args:
utc_offset (Optional[float]): UTC offset in hours. Positive for UTC+, negative for UTC-.
Gives the ``Etc/GMT`` zone of the offset; these exist for whole hours from -12 to +14.
location (Optional[Tuple[float,float]]): A tuple containing latitude and longitude as floats.
as_string (Optional[bool]):
- If `True`, returns the timezone as a string (e.g., "America/New_York").
- If `False` or not provided, returns a `Timezone` object for the timezone.
date_time (Optional[datetime.datetime]): A timezone-aware date-time (also a pandas
``Timestamp`` or a Pendulum ``DateTime``). Gives the named timezone of its ``tzinfo``
(zoneinfo, pytz, Pendulum, ``datetime.timezone.utc``), else the ``Etc/GMT`` zone of
its UTC offset (e.g. for ``UTC+02:00`` fixed offsets or dateutil timezones).
Returns:
Union[Timezone, str]:
@@ -1430,11 +1449,15 @@ def to_timezone(
- A `Timezone` object if `as_string` is `False` or not provided.
Raises:
ValueError: If invalid inputs are provided.
ValueError: If invalid inputs are provided, e.g. a UTC offset without an ``Etc/GMT``
zone (not a whole hour, or outside -12 to +14) or a naive ``date_time``.
Example:
>>> to_timezone(utc_offset=5.5, as_string=True)
'UTC+05:30'
>>> to_timezone(utc_offset=5, as_string=True)
'Etc/GMT-5'
>>> to_timezone(date_time=to_datetime("2024-10-13T15:30:00", in_timezone="Europe/Berlin"), as_string=True)
'Europe/Berlin'
>>> to_timezone(location=(40.7128, -74.0060))
<Timezone [America/New_York]>
@@ -1458,11 +1481,13 @@ def to_timezone(
# NOTE: Etc/GMT sign convention is *inverted* relative to the common
# expectation: Etc/GMT+5 means UTC-5. We therefore flip the sign.
hours = int(utc_offset)
minutes = int((abs(utc_offset) - abs(hours)) * 60)
sign = "-" if utc_offset >= 0 else "+"
offset_str = f"Etc/GMT{sign}{abs(hours)}"
if minutes > 0:
offset_str += f":{minutes:02}"
if hours != utc_offset or not _is_timezone_name(offset_str):
raise ValueError(
f"No timezone for UTC offset {utc_offset} hours: Etc/GMT zones exist for whole "
"hours from -12 to +14 only."
)
if as_string:
return offset_str
@@ -1492,6 +1517,29 @@ def to_timezone(
return tz_name
return pendulum.timezone(tz_name)
# Handle the timezone of a date-time
if date_time is not None:
tzinfo = getattr(date_time, "tzinfo", None)
if tzinfo is None:
raise ValueError(f"Date-time without timezone: {date_time}")
# zoneinfo names its zone `key`, pytz `zone`, Pendulum `name`; str() covers the rest.
for candidate in (
getattr(tzinfo, "key", None),
getattr(tzinfo, "zone", None),
getattr(tzinfo, "name", None),
str(tzinfo),
):
if _is_timezone_name(candidate):
zone_name = _canonicalize_tz_name(cast(str, candidate))
if as_string:
return zone_name
return pendulum.timezone(zone_name)
offset = date_time.utcoffset()
offset_hours = offset.total_seconds() / 3600 if offset is not None else 0.0
if as_string:
return to_timezone(utc_offset=offset_hours, as_string=True)
return to_timezone(utc_offset=offset_hours)
# Fallback to local timezone
local_tz = pendulum.local_timezone()
if isinstance(local_tz, str):
+51 -3
View File
@@ -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,14 +1557,15 @@ class TestToDuration:
# -----------------------------
def test_to_timezone_string():
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():
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)
@@ -1571,13 +1573,59 @@ def test_to_timezone_timezone():
assert result.name == "America/New_York", "Expected Timezone name 'America/New_York'"
def test_to_timezone_invalid_coordinates():
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)
# -----------------------------
# hours_in_day
# -----------------------------
+177
View File
@@ -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()