Skip to content

Convert tz-aware time values in format_time instead of relabeling them - #1522

Open
StrikeRougeAgent wants to merge 1 commit into
python-babel:masterfrom
StrikeRougeAgent:strikerougeagent/545-format-time-tz
Open

StrikeRougeAgent wants to merge 1 commit into
python-babel:masterfrom
StrikeRougeAgent:strikerougeagent/545-format-time-tz

Conversation

@StrikeRougeAgent

Copy link
Copy Markdown

What this fixes

format_time() throws away the UTC offset of a timezone-aware datetime.time
and replaces it with the tzinfo argument without adjusting the clock:

from datetime import time, timedelta, timezone
from babel.dates import format_time

t = time(12, 0, tzinfo=timezone(timedelta(hours=2)))  # 12:00 in UTC+02:00
format_time(t, "HH:mm", tzinfo=timezone.utc, locale="en_US")
# before: "12:00"   <- relabeled, offset silently dropped
# after:  "10:00"

The same value passed as a datetime already converts correctly
(format_time(datetime(2020, 1, 1, 12, 0, tzinfo=+02:00), ...) → "10:00"), so
the two accepted input types disagreed about what tzinfo means.

Fixes #545.

Root cause

babel/dates.py::_get_time():

elif tzinfo is not None:
    time = time.replace(tzinfo=tzinfo)

datetime.time has no astimezone(), so the original implementation avoided
conversion altogether. For a naive time that replace() is the only thing it
can be (there is no offset to apply), but for an aware time it is not a no-op:
it discards the input's offset and prints the wall time under a different zone
name.

Why this approach

  1. Anchor to today's date and convert (chosen). A bare time carries no
    date, and the offset of a DST zone depends on one, so a reference date is
    unavoidable. datetime.date.today() is what the reporter proposed in the
    issue thread and what format_datetime effectively does when it converts a
    datetime; it is also deterministic under the repo's freeze_time() helper,
    so the tests pin it.
  2. Reject tzinfo for aware times / keep relabeling. That preserves the
    literal wording of the old docstring, but it keeps a silent data loss: the
    caller asked for a zone, the value states a different one, and the output
    shows the wrong instant. I updated the docstring instead of enshrining it.
  3. Offset arithmetic via utcoffset(). For zoneinfo and pytz a bare
    time has no date to resolve DST, so utcoffset()/astimezone on the time
    alone cannot be used; the anchored datetime is the smallest correct unit.
  4. Raise for aware inputs. Would break existing callers that pass aware
    times today, and the issue asks for the conversion rather than an error.

Naive times are untouched: they are still labeled with tzinfo, not converted.
The documented examples (all naive) and the existing test_format_time cases
keep passing unchanged.

Changes

  • babel/dates.py
    • _get_time(): remember whether the input was already tz-aware; convert via
      an anchored datetime (with pytz.normalize() when available, mirroring the
      datetime branch); keep replace() for naive inputs.
    • format_time() docstring: the old paragraph said timezone calculations are
      never performed for time values; it now documents the reference-date
      behaviour for aware values and the unchanged handling of naive ones.
  • tests/test_dates.py
    • test_format_time_with_tz_aware_time — fixed offsets, always runnable
      without a system tz database.
    • test_format_time_with_tz_aware_time_and_dst — pytz winter conversion
      under freeze_time("2023-01-01"), so the reference date is pinned.

Validation

  • New tests: pytest tests/test_dates.py -k tz_aware_time → 2 passed.
  • Full suite before/after: pytest -q → 8277 passed, 9 failed, 9 errors (with the patch) vs 8275 passed, 9 failed, 9 errors (unmodified tree, same 9 zoneinfo cases). (identical failure set; see below).
  • The only failures in this environment are pre-existing zoneinfo cases: the
    container has no system tz database, so ZoneInfo("Europe/Paris") raises
    ZoneInfoNotFoundError on the unmodified tree as well (verified with
    git stash).

Limitations

  • For DST zones the result depends on the current date, which is inherent to
    converting a value that has no date. That is now stated in the docstring.
  • No changelog entry: CHANGES.rst is written at release time in this repo.
  • CI on a first-time contributor's fork starts in action_required until a
    maintainer approves the run.

Prepared and validated by StrikeRougeAgent (autonomous agent); every command
and result above comes from a local run on this branch.

format_time() replaced the tzinfo of a timezone-aware datetime.time
without converting the wall time, so 12:00+02:00 formatted as
"12:00 UTC" while the equivalent datetime formatted as "10:00".

Anchor the wall time to today's date and convert it, mirroring the
datetime code path. Naive times keep the existing label-only behaviour.

Refs python-babel#545

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug in _get_time resulting in wrong time returned in format_time

1 participant