perf(datetimeutil): parse ISO 8601 instants without the format search

to_datetime() tried ten pendulum formats before an ISO 8601 date-time
with "Z" or an explicit offset reached pendulum.parse(). None of the
formats can match such a string (each is combined with a timezone
name), so every call paid ~190 µs for nothing. Database timestamps
("20241027T123456Z") take this path on every record lookup
(db_get_record, _db_timestamp_after, key_from_series), and so do API
and provider date-times.

These strings name one instant and are now parsed directly (~7 µs),
built with pendulum.datetime() like pendulum.parse(), so the result
keeps the same fold. Any other form, offsets of 24 hours or more and
out-of-range fields still go through the generic parser. Compared with
the previous to_datetime() over 162 432 calls (5076 strings, 8 target
zones): no difference in value, timezone, fold or raised exception.

DatabaseTimestamp.from_datetime() formats with an f-string instead of
the format-token parser of pendulum (6 µs -> 2 µs), with the same output
for every 4-digit year. Its docstring example shows the stored form
"20241027T123456Z".

The five DB/EnergyCharts test modules: 298 s -> 112 s.

Additional changes
Test the config returned to a re-entrant get_config(); the full suite
reached that line only as a side effect of slow tests

Refs #1553

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
SchaafAlexander
2026-11-20 07:15:33 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent cc875f798c
commit 00a39f75bf
5 changed files with 159 additions and 2 deletions
+13
View File
@@ -1,6 +1,7 @@
import json
import tempfile
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import Mock, patch
@@ -1042,3 +1043,15 @@ class TestConfigSetup:
with pytest.raises(RuntimeError, match="before its settings are loaded"):
coreabc.get_config(init=True)
def test_access_after_settings_are_loaded_returns_config_in_setup(
self, uncreated_config, monkeypatch
):
"""During creation the configuration is returned once its settings are loaded."""
from akkudoktoreos.core import coreabc
config_in_setup = SimpleNamespace(_initialized=True)
monkeypatch.setattr(coreabc, "_config_eos_setup_running", True)
monkeypatch.setitem(ConfigEOS._instances, ConfigEOS, config_in_setup)
assert coreabc.get_config(init=True) is config_in_setup
+33
View File
@@ -361,6 +361,39 @@ async def seq_sparse():
return s, now
# ---------------------------------------------------------------------------
# DatabaseTimestamp
# ---------------------------------------------------------------------------
class TestDatabaseTimestamp:
@pytest.mark.parametrize(
("local", "timezone", "expected"),
[
# 02:30:59 occurs twice on the day DST ends.
("2024-10-27T02:30:59+02:00", "Europe/Berlin", "20241027T003059Z"),
("2024-10-27T02:30:59+01:00", "Europe/Berlin", "20241027T013059Z"),
("2026-01-01T00:00:00+14:00", "Pacific/Kiritimati", "20251231T100000Z"),
("2026-01-01T23:59:59-12:00", "Etc/GMT+12", "20260102T115959Z"),
],
)
def test_round_trip(self, local: str, timezone: str, expected: str) -> None:
dt = to_datetime(local, in_timezone=timezone)
db_ts = DatabaseTimestamp.from_datetime(dt.add(microseconds=999))
assert db_ts == expected
assert db_ts == dt.in_timezone("UTC").format("YYYYMMDDTHHmmss[Z]")
parsed = db_ts.to_datetime()
# Compare in UTC: an inter-zone comparison is never equal for the
# second (fold=1) occurrence of an ambiguous local time.
assert parsed == dt.in_timezone("UTC")
assert parsed.timezone_name == "UTC"
def test_naive_datetime_rejected(self) -> None:
with pytest.raises(ValueError):
DatabaseTimestamp.from_datetime(DateTime(2024, 1, 1))
# ---------------------------------------------------------------------------
# Core mixin tests
# ---------------------------------------------------------------------------
+43
View File
@@ -963,6 +963,49 @@ def test_to_datetime_explicit_offset_preserves_instant(
assert actual.timezone_name == "Europe/Berlin"
@pytest.mark.parametrize("in_timezone", ["UTC", "Europe/Berlin", "Pacific/Kiritimati", "Etc/GMT+12"])
@pytest.mark.parametrize(
"value",
[
"2024-10-27T00:30:00Z", # 02:30 CEST in Berlin, first occurrence
"2024-10-27T01:30:00Z", # 02:30 CET in Berlin, second occurrence
"2024-10-27T02:30:00.25+01:00",
"2025-12-31T23:59:59.999999-12:00",
"2026-01-01T00:00:00+14:00",
"2024-06-15T12:00:00+05:45",
"20241027T013000Z", # basic form of database timestamps
],
)
def test_to_datetime_iso_instant_matches_generic_parser(value: str, in_timezone: str) -> None:
"""ISO 8601 instants skip the format search and still match pendulum.parse, fold included."""
expected = cast(pendulum.DateTime, pendulum.parse(value)).in_timezone(in_timezone)
actual = to_datetime(value, in_timezone=in_timezone)
naive = to_datetime(value, in_timezone=in_timezone, to_naiv=True)
assert actual.isoformat() == expected.isoformat()
assert actual.fold == expected.fold
assert actual.timezone_name == in_timezone
assert naive.isoformat() == expected.naive().isoformat()
assert naive.fold == expected.naive().fold
@pytest.mark.parametrize(
"value",
[
"2024-13-01T00:00:00Z",
"2024-02-30T12:00:00+01:00",
"20241327T000000Z",
"2024-01-01T00:00:00+24:00",
],
ids=["month-13", "february-30", "basic-month-13", "offset-24h"],
)
def test_to_datetime_iso_instant_out_of_range_raises(value: str) -> None:
"""An ISO 8601 instant with an out-of-range field is still rejected."""
with pytest.raises(ValueError):
to_datetime(value, in_timezone="UTC")
@pytest.mark.parametrize(
"value",
[1768517100, 1768517100.123456, "1768517100.123456"],