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
+9 -2
View File
@@ -299,7 +299,7 @@ class DatabaseTimestamp(str):
Must always be in UTC and lexicographically sortable.
Example:
"20241027T123456[Z]" # 2024-10-27 12:34:56
"20241027T123456Z" # 2024-10-27 12:34:56 UTC
"""
__slots__ = ()
@@ -309,9 +309,16 @@ class DatabaseTimestamp(str):
if dt is None or dt.tz is None:
raise ValueError("Timezone-aware datetime required")
return cls(dt.in_timezone("UTC").format("YYYYMMDDTHHmmss[Z]"))
# Same result as format("YYYYMMDDTHHmmss[Z]") for 4-digit years, without
# pendulum's format-token parser (called for every record access).
utc = dt.in_timezone("UTC")
return cls(
f"{utc.year:04d}{utc.month:02d}{utc.day:02d}"
f"T{utc.hour:02d}{utc.minute:02d}{utc.second:02d}Z"
)
def to_datetime(self) -> DateTime:
# to_datetime() parses the canonical form directly (ISO 8601 instant fast path).
return to_datetime(self, in_timezone="UTC")
+61
View File
@@ -851,6 +851,63 @@ def to_time(
raise ValueError(f"Invalid time value: {value!r} of type: {type(value)}") from e
# ISO 8601 date-times that name one instant: an explicit "Z" or UTC offset, e.g.
# "2024-10-13T15:30:00Z", "2024-10-13T15:30:00.250+02:00", or the basic form
# "20241013T153000Z" of database timestamps.
_ISO_INSTANT_EXTENDED = re.compile(
r"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|[+-]\d{2}:\d{2})",
re.ASCII,
)
_ISO_INSTANT_BASIC = re.compile(r"(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z)", re.ASCII)
def _parse_iso_instant(value: str) -> Optional[pendulum.DateTime]:
"""Parse an ISO 8601 date-time with an explicit UTC designator or offset.
These strings match none of the formats that `to_datetime` tries first (each is
combined with a timezone name), so they used to reach `pendulum.parse` only after
every format had failed. Parsing them directly gives the same instant at a
fraction of the cost; this path carries most string conversions in EOS, such as
database timestamps and API date-times.
Args:
value: The date-time string.
Returns:
The parsed date-time in the given offset, or None if `value` has another form
or an out-of-range field, so the caller can fall back to the generic parser.
"""
match = _ISO_INSTANT_EXTENDED.fullmatch(value) or _ISO_INSTANT_BASIC.fullmatch(value)
if match is None:
return None
year, month, day, hour, minute, second = (int(match.group(i)) for i in range(1, 7))
fraction = match.group(7) if match.re is _ISO_INSTANT_EXTENDED else None
offset = match.group(match.re.groups)
tzinfo: Timezone | pendulum.FixedTimezone
if offset == "Z":
tzinfo = UTC
else:
offset_minutes = int(offset[1:3]) * 60 + int(offset[4:6])
if offset_minutes >= 24 * 60:
return None
tzinfo = pendulum.FixedTimezone((-1 if offset[0] == "-" else 1) * offset_minutes * 60)
try:
# pendulum.datetime() is the factory pendulum.parse() uses, so the result also
# keeps the fold attribute that the generic path returns.
return pendulum.datetime(
year,
month,
day,
hour,
minute,
second,
int(fraction.ljust(6, "0")) if fraction else 0,
tz=tzinfo,
)
except ValueError:
return None
@overload
def to_datetime(
date_input: Optional[Any] = None,
@@ -963,6 +1020,10 @@ def to_datetime(
dt = dt.end_of("day")
else:
dt = dt.start_of("day")
elif (
isinstance(date_input, str) and (iso_instant := _parse_iso_instant(date_input)) is not None
):
dt = iso_instant
elif isinstance(date_input, str):
# Convert to timezone aware datetime
dt = None