Before accepting an agent-written Python scheduler, test whether each submitted local date and time identifies zero, one, or two UTC instants in its named time zone. Reject a missing time during a clock jump. Require an explicit earlier-or-later choice for a repeated time. Convert the accepted result to UTC before comparing execution instants.

Attaching ZoneInfo with replace(tzinfo=...) does not perform this validation. A plausible-looking aware datetime can still represent a local clock reading that never occurred. The runnable fixture below makes those cases observable without waiting for a real daylight-saving transition.

Last reviewed: 2026-11-20 (Asia/Shanghai). Official sources checked on 2026-11-19 UTC, the same local day.

Define what a submitted local time means

This review applies when an agent changes appointment creation, scheduled reports, reminder delivery, or another feature that accepts a local clock reading. Start with three separate inputs: a date and time without an offset, an IANA zone key such as America/New_York, and a policy for repeated or missing readings.

PEP 495: Local Time Disambiguation calls a backward-clock interval a fold and a forward-clock interval a gap. A reading inside a fold is ambiguous; one inside a gap is missing. These transitions can have causes other than daylight saving and shifts other than one hour. Avoid implementing validation by adding or subtracting a hard-coded hour.

For this example, the acceptance policy is deliberately explicit:

Local readingNumber of valid instantsApplication response
Ordinary date and timeOneAccept and return that UTC instant
Spring gapZeroReject with nonexistent_local_time
Autumn fold without a choiceTwoReject with ambiguous_local_time
Autumn fold with earlier or laterTwoReturn the selected UTC instant
Unknown zone keyNo resolution availableSurface the zone error; do not use the host zone

Those responses are application decisions. Python does not mandate that every product reject gaps: a scheduling product might deliberately skip a missing occurrence or move it according to a documented rule. If yours does, specify that behavior separately and assert the exact resulting date, time, and instant. An agent should not silently invent the policy while fixing a failing test.

Keep an already specified instant on a different input path. An offset-bearing timestamp and a naive local appointment are different contracts. This resolver rejects aware input to avoid accidentally stripping an offset and reinterpreting it as local time. Validate the application’s scheduling horizon and zone-key input at the request boundary; this fixture handles conversion rather than request parsing or recurrence expansion.

Validate through UTC before accepting the schedule

The official ZoneInfo reference documents both fold values: during a repeated interval, fold=0 selects the pre-transition offset and fold=1 the post-transition offset. Conversion from UTC sets the appropriate fold automatically. PEP 495 also states that constructors and replace() do not check whether the result is a valid local time.

The resolver therefore tries both interpretations, converts each to UTC, and converts it back to the requested zone. It retains only candidates whose returned local fields match the submitted fields. Deduplicating the UTC candidates yields one instant for ordinary readings, none for gaps, and two for folds.

The intermediate UTC conversion matters. The datetime reference says astimezone() performs no adjustment when the target is the object’s existing time-zone object. Calling local.astimezone(zone) directly would not establish the round trip this validation needs.

Save the complete example as test_local_schedule.py. It uses standard-library APIs available in Python 3.9 and newer, plus accessible IANA time-zone data. The article’s local run used CPython 3.12.3 and system tzdata 2026e.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import unittest


def resolve_local(wall, zone_key, *, occurrence=None):
    """Resolve a naive wall-clock reading to one UTC instant."""
    if wall.tzinfo is not None:
        raise ValueError("expected_naive_local_time")
    if occurrence not in (None, "earlier", "later"):
        raise ValueError("invalid_occurrence")

    zone = ZoneInfo(zone_key)
    wall = wall.replace(fold=0)
    candidates = set()
    for fold in (0, 1):
        local = wall.replace(tzinfo=zone, fold=fold)
        instant = local.astimezone(timezone.utc)
        returned = instant.astimezone(zone).replace(tzinfo=None, fold=0)
        if returned == wall:
            candidates.add(instant)

    ordered = sorted(candidates)
    if not ordered:
        raise ValueError("nonexistent_local_time")
    if len(ordered) == 1:
        return ordered[0]
    if occurrence is None:
        raise ValueError("ambiguous_local_time")
    return ordered[0] if occurrence == "earlier" else ordered[-1]


class LocalScheduleTests(unittest.TestCase):
    zone_key = "America/New_York"

    def test_ordinary_time(self):
        self.assertEqual(
            resolve_local(datetime(2026, 2, 1, 9), self.zone_key),
            datetime(2026, 2, 1, 14, tzinfo=timezone.utc),
        )

    def test_spring_gap_is_rejected(self):
        for occurrence in (None, "earlier", "later"):
            with self.subTest(occurrence=occurrence):
                with self.assertRaisesRegex(ValueError, "^nonexistent_local_time$"):
                    resolve_local(
                        datetime(2026, 3, 8, 2, 30), self.zone_key,
                        occurrence=occurrence,
                    )

    def test_autumn_fold_requires_choice(self):
        with self.assertRaisesRegex(ValueError, "^ambiguous_local_time$"):
            resolve_local(datetime(2026, 11, 1, 1, 30), self.zone_key)

    def test_fold_choices_are_distinct_instants(self):
        wall = datetime(2026, 11, 1, 1, 30)
        earlier = resolve_local(wall, self.zone_key, occurrence="earlier")
        later = resolve_local(wall, self.zone_key, occurrence="later")
        self.assertEqual(earlier, datetime(2026, 11, 1, 5, 30, tzinfo=timezone.utc))
        self.assertEqual(later, datetime(2026, 11, 1, 6, 30, tzinfo=timezone.utc))
        self.assertEqual(later - earlier, timedelta(hours=1))

    def test_transition_edges(self):
        cases = [
            (datetime(2026, 3, 8, 1, 59, 59), datetime(2026, 3, 8, 6, 59, 59, tzinfo=timezone.utc)),
            (datetime(2026, 3, 8, 3), datetime(2026, 3, 8, 7, tzinfo=timezone.utc)),
        ]
        for wall, expected in cases:
            with self.subTest(wall=wall):
                self.assertEqual(resolve_local(wall, self.zone_key), expected)

    def test_input_contract(self):
        with self.assertRaisesRegex(ValueError, "^expected_naive_local_time$"):
            resolve_local(datetime(2026, 2, 1, 9, tzinfo=timezone.utc), self.zone_key)
        with self.assertRaisesRegex(ValueError, "^invalid_occurrence$"):
            resolve_local(datetime(2026, 2, 1, 9), self.zone_key, occurrence="guess")

    def test_missing_zone_is_not_replaced_by_host_zone(self):
        with self.assertRaises(ZoneInfoNotFoundError):
            resolve_local(datetime(2026, 2, 1, 9), "Etc/ArticleMissingZone")

    def test_local_equality_can_hide_the_fold(self):
        zone = ZoneInfo(self.zone_key)
        first = datetime(2026, 11, 1, 1, 30, tzinfo=zone, fold=0)
        second = first.replace(fold=1)
        self.assertEqual(first, second)
        self.assertEqual(second - first, timedelta(0))
        self.assertEqual(
            second.astimezone(timezone.utc) - first.astimezone(timezone.utc),
            timedelta(hours=1),
        )

    def test_next_local_day_is_not_always_24_elapsed_hours(self):
        zone = ZoneInfo(self.zone_key)
        start = datetime(2026, 3, 7, 9, tzinfo=zone)
        next_wall_day = start + timedelta(days=1)
        self.assertEqual(next_wall_day.hour, 9)
        self.assertEqual(
            next_wall_day.astimezone(timezone.utc) - start.astimezone(timezone.utc),
            timedelta(hours=23),
        )
        after_24_hours = start.astimezone(timezone.utc) + timedelta(hours=24)
        self.assertEqual(after_24_hours.astimezone(zone).hour, 10)


if __name__ == "__main__":
    unittest.main(verbosity=2)

Run the focused fixture:

python3 -m unittest -v test_local_schedule

The expected output is nine passing tests followed by OK. That result was observed for this exact fixture in the environment stated above. It establishes the demonstration’s behavior, rather than the correctness of your application’s scheduler, persistence, or delivery system.

Compare instants without losing the repeated hour

In the New York fixture, November 1, 2026 at 01:30 occurs at both 05:30 UTC and 06:30 UTC. The choice test asserts these absolute expected values independently of the resolver. Checking only that the returned local hour is 1 would accept either occurrence and miss a one-hour scheduling error.

Beware of using local aware objects as the candidate set. The datetime reference specifies that comparison between aware datetimes sharing the same tzinfo object ignores their fold attributes. Its subtraction rules also ignore time-zone adjustments for that same-zone case. The test intentionally demonstrates that the two local objects compare equal and subtract to zero, while their UTC forms differ by an hour.

This is why the resolver stores UTC objects before deduplication. It also normalizes the input’s fold field: the separate occurrence argument owns the ambiguity decision. A hidden fold value on a naive input must not silently override that policy.

As a negative control, replace the resolver temporarily with an implementation that only attaches ZoneInfo and converts to UTC. The gap-rejection, missing-choice, and distinct-choice assertions should fail. That substitution was tried locally and those failures were observed. Keep the acceptance assertions intact when asking the agent to repair the implementation.

Distinguish tomorrow at nine from twenty-four hours later

A daily local appointment and an elapsed-duration timer need different calculations. The final test starts at 09:00 in New York on March 7, 2026. Adding one local calendar day yields 09:00 on March 8; only 23 hours pass between the corresponding UTC instants. Adding 24 hours in UTC instead yields 10:00 local time on March 8.

These are different requirements, so state which one the patch implements. The datetime reference documents that adding a timedelta keeps the same tzinfo and performs no time-zone adjustment to the date and time fields. A green test that checks only the local hour cannot prove an elapsed-duration promise.

For a recurring local schedule, generate the next intended local date and time, then apply the gap/fold policy again. Do not assume that adding a day to an aware value validates the next occurrence. For an elapsed deadline, calculate the intended instant in UTC; use the application’s elapsed-time clock when enforcing a running timeout.

The site’s virtual-clock testing guide explains how to control timer advancement once the correct deadline has been chosen. Calendar resolution and timer execution need separate assertions.

Record the time-zone rules the tests actually used

ZoneInfo obtains rules from the system database first, then falls back to the first-party tzdata package if necessary. The official reference warns that neither source is guaranteed on every platform. A missing database or zone raises ZoneInfoNotFoundError; do not repair the test by substituting the machine’s local zone or a fixed offset.

Record the interpreter patch version and the actual rule source in the review. Merely pinning the tzdata package does not force its use when system rules are found first. If a test environment deliberately selects the package, the reference documents setting PYTHONTZPATH to an empty string before starting Python. Ensure that the package is installed and managed by the project’s dependency policy.

The local verification here used system rules identified as 2026e. Treat the New York dates and offsets as explicit fixtures for those rules, not universal transition dates. Extend the suite with the zones the product supports, including a non-hour transition if relevant. Re-run the expected instants after a time-zone-data update and inspect changes rather than bulk-refreshing assertions.

For a one-time appointment, retain its accepted UTC instant along with the original local request, zone key, and ambiguity choice as appropriate for the product. For future recurring schedules, document whether rule updates may change future resolved instants. Those are persistence and product policies beyond this in-memory resolver.

Give the coding agent a failing occurrence to repair

Adapt one real submission path to the fixture before expanding the scheduler. Capture an ordinary time, a missing time, both repeated-time choices, and the UTC instant that actually reaches the scheduling boundary. An error response must leave no accepted scheduled action behind. The unit resolver cannot prove that integration property; add an assertion against a fake scheduling sink or the existing component test.

Run the adapted checks against the base revision and the proposed patch with the same interpreter and rule source. Include the test command, exit result, zone key, synthetic case identifier, chosen policy, and expected UTC value in the review. Distinguish an input rejection from unavailable time-zone data so deployment failures cannot appear as user mistakes.

Use a bounded coding-agent task brief to state the gap/fold policy before the repair. Ask the agent to preserve the expected instants and error cases, repair the conversion path, and report any separate recurrence-policy decision. Start with the first missing or repeated occurrence your current code accepts incorrectly.

Sources checked

These three primary references were retrieved successfully on November 19, 2026 UTC. They support an evergreen implementation task; the older PEP supplies the normative fold semantics, and the maintained library references supply the current API behavior. The fixture uses Python 3.9+ APIs and was executed on CPython 3.12.3.