A request such as “send the reminder tomorrow at nine” contains more engineering work than its wording suggests. Tomorrow depends on a calendar and a location. Nine is a reading on a local clock. A reminder also needs an actual instant when it should become eligible to run. If those meanings become mixed together, apparently reasonable generated code can send something an hour early, accept a time that never occurred, or choose one of two repeated times without asking.

Use DeepSeek to expose these decisions, propose a small implementation, and help explain failing cases. Keep the authority for the decisions in a written contract and the authority for correctness in tests you can execute independently. This guide develops that workflow around a deliberately narrow problem: resolving an explicitly supplied local date and time in a named time zone to one unambiguous instant, with a canonical local representation and a verifiable UTC equivalent.

The prompts, scenarios, and examples below are authored for this tutorial. They are not transcripts of a DeepSeek session, and no model performance claim is implied. The Python example is a teaching component, not a complete scheduling service. Historical dates make the central examples repeatable; documentation and reference sources were checked on October 4, 2026.

Separate five meanings of time

Before sending a code snippet to DeepSeek, label the meaning of every time-related value. A field called time or date gives the model very little help. In a fictional room-booking application, the creation time of a reservation, the requested starting time, and the day shown in a calendar grid need different rules even if all three currently live in the same database column type.

  • An instant identifies one point on the timeline. A booking audit event needs this meaning because two viewers in different locations should still be discussing the same event. Its presentation may change without changing which event it records.
  • A wall-clock date and time describes the calendar and clock reading intended at a location. “November 3, 2024, at 01:30 in New York” belongs here. The conversion step must establish whether that reading identifies zero, one, or two possible instants.
  • A date-only value expresses a calendar day without inventing a time. A selected attendance day may be a date-only business concept. Turning it into midnight merely to fit an existing timestamp field introduces a decision that the original value never contained.
  • An elapsed duration measures an interval such as ninety minutes or twenty-four hours. Its use should answer a question about how much time passes, with the measurement method chosen for the task.
  • A recurrence describes how to generate future occurrences. “Every weekday at 09:00 in the office zone” includes a rule, a zone, and policies for exceptional dates. One computed UTC instant cannot preserve that whole intention.

A numeric UTC offset and a named zone also serve different purposes. An offset such as -04:00 is sufficient, together with a complete date and time, to identify an instant. It does not tell a later occurrence which offset to use. A named zone such as America/New_York points to a set of civil-time rules. RFC 3339 provides a useful timestamp representation with an offset; a separate zone field preserves location-based scheduling intent. [4, 6]

Ask the model to classify existing fields before recommending transformations. If it cannot tell whether a value is an instant or an appointment intention, leave that as a question for the product owner. Renaming a field can be a useful first change: requested_local_start tells a reviewer far more than start_timestamp. Keep this inventory short enough to review next to the function under discussion.

Five time concepts: instant, local wall time with a zone, calendar date, elapsed duration, and local recurrence. Each needs a different input and decision contract.
Choose the meaning before choosing a datetime representation. A calendar date should not silently become a zoned midnight.

Write a contract before requesting code

For the worked example, define one operation: accept a local Python datetime with no attached zone, a valid IANA zone key, and an optional repeated-time policy; return a canonical aware datetime in that zone or a clear error. Its UTC conversion identifies the chosen instant. The local input is intentionally incomplete until paired with its zone. This interface should never infer the zone from a server, a browser locale, an IP address, or the language of a prompt.

Choose the exceptional behavior before implementation. This tutorial rejects a local reading that falls in a clock-change gap. It requires an explicit earlier or later choice when the reading occurs twice. An ordinary reading is accepted only with no occurrence selector, so a stale earlier-or-later decision produces an error. These are tutorial policies selected for clarity. Another product may reasonably choose different behavior, but its owner should approve that behavior and express it in tests.

Write failure behavior at the same level of detail as successful behavior. A missing zone should be an input error. An unavailable zone key should remain distinguishable from a clock-change gap. An already-aware datetime should be rejected by this local-input interface rather than stripped of its offset. An unsupported policy name should fail even when the particular input happens to be ordinary. That last condition prevents invalid configuration from hiding until a transition day.

The teaching implementation accepts exact built-in datetime objects with tzinfo=None and fold=0. It bounds the input year to 1970 through 2099 inclusive; the corresponding UTC instant may cross into an adjacent year. A separate occurrence argument owns the fold choice. These deliberate limits keep the example reviewable and should be reconsidered explicitly if your application needs a broader input domain.

Also decide what the operation does not promise. This resolver does not parse free-form sentences, choose an account’s default zone, generate recurring appointments, compute holidays, or guarantee that a background job runs exactly on time. It does not implement leap-second handling. Keeping those responsibilities outside the example makes a passing test meaningful: the result demonstrates one conversion contract, rather than suggesting that an entire product’s time behavior has been solved.

If a request arrives as “make this DST-safe,” rewrite it into observable statements before asking for code. The requirements workflow can help turn a broad intention into acceptance criteria. For this task, the important output is a small decision record naming the input meanings, exceptional policies, result representation, and person responsible for approving policy changes.

Ask DeepSeek to find missing decisions

Begin with a reasoning request that stops short of implementation. This creates an opportunity to discover a missing decision before a plausible function makes it feel settled. Give the model concrete domain language, a narrow boundary, and a prohibition on silently selecting product policy. Do not ask it to infer intent from the mere presence of a datetime library.

The following prompt is meant to be adapted with non-sensitive examples. Replace ambiguous phrases with actual field meanings whenever they are already known. If production records contain personal details, reduce them to a minimal invented case before using them in a model interaction.

Prompt 1: Contract before code

I am designing a local-time resolver for a room-booking application. Do not write code yet. The inputs are an exact built-in Python datetime containing a local calendar date and clock reading, an explicit IANA zone key, and an optional occurrence policy. The local input must have tzinfo=None, fold=0, and a year from 1970 through 2099 inclusive. The result must be a canonical aware datetime in the supplied zone, identifying one instant whose UTC value we can verify.

Classify each input by meaning. Identify every remaining product decision and separate it from a library behavior that can be checked in documentation. Our chosen policies are: reject nonexistent local times; require earlier or later for repeated times; require no occurrence selector for unique times; reject already-aware local inputs; reject unsupported policy values; never infer a missing zone. Do not change these policies.

Return a compact contract, a list of unresolved questions, and acceptance cases with expected outcomes. Mark anything you are unsure about. Do not claim to have executed code. Do not expand this into a scheduler or select policies that I have not supplied.

Review its questions before proceeding. A question about whether to move a missing 02:30 appointment to 03:00 or 03:30 is useful because those are different commitments. A confident recommendation without that distinction is less useful. Resolve questions in the contract, not in a passing comment that will disappear when someone copies the generated function.

Preserve the final contract separately from the conversation. Later prompts should refer to the same approved text. Otherwise, a repair session can quietly evolve the specification: a rejection becomes a normalization, an optional choice acquires a default, or an input error starts using the machine’s local zone. Those changes deserve a product review even when they reduce the number of failing tests.

Understand the three historical cases

The example uses three New York cases from 2024. Keeping the dates fixed avoids a test that changes meaning when “this year” changes. These cases are small enough to reason about on paper and strong enough to expose different classes of error. Treat the stated UTC results as independent expected values, not as values to regenerate by calling the function being tested.

First, 2024-03-10 02:30 in America/New_York is a missing local reading. The clock moved forward across that part of the local morning. Under our contract, the correct outcome is rejection. Attaching a zone object and obtaining a formatted offset is not proof that an actual instant corresponds to the requested reading.

Second, 2024-11-03 01:30 occurred twice in New York. The earlier occurrence corresponds to 2024-11-03 05:30 UTC, and the later occurrence corresponds to 2024-11-03 06:30 UTC. Without a policy, our function rejects the ambiguity. With a policy, the expected result is one of those two specific instants.

Third, start at noon in New York on March 9, 2024. Adding twenty-four elapsed hours reaches 13:00 local time on March 10. Asking for noon on the next local calendar day reaches an instant only twenty-three elapsed hours later. Both operations are coherent. A requirement that merely says “add one day” leaves the implementation underdetermined.

PEP 495 calls repeated local readings a fold and missing readings a gap. Its fold flag distinguishes the earlier and later occurrences, but constructing a datetime does not itself validate whether the local reading exists. Changes in offset can also differ from the familiar one-hour seasonal change. [3]

Use the diagram and these exact values during review. Ask a teammate to explain which input fact selects the instant before showing them any code. If the explanation requires guessing what a default means, refine the interface. A concise failing example is often more productive than a broad discussion about whether a library “handles DST.”

In New York on March 10, 2024, 02:30 has no matching instant. On November 3, 01:30 occurs at both 05:30 UTC and 06:30 UTC. The resolver rejects gaps and requires an explicit earlier or later fold choice.
Historical New York examples. Round-trip candidate local times through UTC and count distinct matching UTC instants.

Resolve local time through UTC candidates

A useful teaching approach is to propose both fold interpretations, convert each candidate to UTC, and convert it back into the requested zone. Keep a candidate only if the returned calendar and clock fields reproduce the supplied local reading. Deduplicate retained candidates by their UTC instant. The remaining set expresses the decision the application must make.

With zero retained instants, the local reading is missing under the loaded zone rules. With one, it is ordinary. With two, it needs the approved earlier-or-later decision. Sorting those UTC candidates gives the ambiguity policy a direct chronological meaning. The chosen instant is converted back to the named zone for the function’s canonical return value. This is easier to audit than a branch that equates “earlier” with a particular offset sign or with a seasonal abbreviation.

The round trip is important because candidate construction is intentionally permissive. It is a way to ask the zone rules a question, not an assertion that the constructed local time is valid. Comparing only two candidate offsets would answer a weaker question: differing offsets alone do not demonstrate that both interpretations are real occurrences of the requested reading.

Deduplication matters on ordinary dates. Trying two fold values there may lead to the same UTC instant. If the code simply counts attempts, it could label every ordinary input ambiguous. Keep identity in UTC for this step. Local representations can share clock fields while standing for different instants, which is precisely the problem the resolver is meant to settle.

The compact implementation belongs below. Read it as one possible realization of the contract, then run the companion cases in your own environment. Its input checks, candidate construction, round-trip filter, UTC deduplication, and policy selection should each have a visible purpose. If a generated replacement merges those steps, require an explanation of how the same checks remain enforceable.

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

UTC = timezone.utc  # datetime.UTC requires Python 3.11; this also works on 3.10.
MIN_YEAR, MAX_YEAR = 1970, 2099


class NonexistentTimeError(ValueError):
    """The requested wall time falls in a clock-forward gap."""


class AmbiguousTimeError(ValueError):
    """The requested wall time needs an explicit occurrence."""


def valid_utc_instants(wall: datetime, zone_key: str) -> tuple[datetime, ...]:
    """Return zero, one, or two distinct UTC instants, in chronological order."""
    if type(wall) is not datetime or wall.tzinfo is not None:
        raise TypeError("wall must be a built-in datetime with tzinfo=None")
    if wall.fold != 0:
        raise ValueError("wall.fold must be 0; use occurrence to choose a fold")
    if not MIN_YEAR <= wall.year <= MAX_YEAR:
        raise ValueError(f"wall year must be {MIN_YEAR}..{MAX_YEAR}")
    if not isinstance(zone_key, str):
        raise TypeError("zone_key must be an IANA key string")
    if not zone_key:
        raise ValueError("zone_key must not be empty")
    zone = ZoneInfo(zone_key)  # Missing data/key: propagate ZoneInfoNotFoundError.
    instants = set()
    for fold in (0, 1):
        # Attaching tzinfo creates a hypothesis; it does NOT validate wall.
        candidate = wall.replace(tzinfo=zone, fold=fold)
        instant = candidate.astimezone(UTC)
        restored = instant.astimezone(zone)
        if restored.replace(tzinfo=None, fold=0) == wall:
            instants.add(instant)  # Compare/deduplicate UTC, never local datetimes.
    return tuple(sorted(instants))


def classify_local(wall: datetime, zone_key: str) -> str:
    """Return 'gap', 'unique', or 'fold'; input errors still raise."""
    return ("gap", "unique", "fold")[len(valid_utc_instants(wall, zone_key))]


def resolve_local(
    wall: datetime, zone_key: str, occurrence: str | None = None
) -> datetime:
    """Resolve a wall time; never silently shift a gap or choose a fold."""
    if occurrence not in (None, "earlier", "later"):
        raise ValueError("occurrence must be None, 'earlier', or 'later'")
    instants = valid_utc_instants(wall, zone_key)
    if not instants:
        raise NonexistentTimeError(f"{wall.isoformat()} does not exist in {zone_key}")
    if len(instants) == 2 and occurrence is None:
        raise AmbiguousTimeError("choose occurrence='earlier' or 'later'")
    if len(instants) == 1 and occurrence is not None:
        raise ValueError("occurrence is only allowed for an ambiguous wall time")
    instant = instants[-1] if occurrence == "later" else instants[0]
    return instant.astimezone(ZoneInfo(zone_key))

Keep parsing outside this function. A parser should establish the accepted textual shape and produce the promised local value. The resolver should establish whether that value has an acceptable interpretation in the supplied zone. This separation makes a malformed string, an unavailable zone, a missing time, and an ambiguous time individually testable.

Generate a candidate against fixed tests

Once the policy is settled, DeepSeek can be asked for a candidate implementation. Supply the approved contract and a test file whose expected outcomes are already written down. Keeping the tests fixed prevents the model from making a mistaken implementation appear correct by changing the expected results to match it.

Prompt 2: Candidate generator under fixed tests

Implement only the local-time resolver described in the attached contract. Use Python datetime and zoneinfo. Propose both fold interpretations, round-trip through UTC, keep only candidates that return the requested local fields, and deduplicate by UTC instant. Reject gaps. Require earlier or later for two candidates. Reject any occurrence selector for a unique reading. Return the chosen instant converted back into the supplied named zone.

The supplied tests and their expected values are fixed. Do not edit them, weaken assertions, hard-code particular transition dates, add a server-local default, or change our exception policies. If you believe a test conflicts with the contract, identify the conflict separately and wait for a decision.

Return the function, a short explanation of its branches, and any assumptions that still need checking. Do not say tests passed unless you actually executed them and can report the environment and output. Do not add networking, storage, background jobs, or recurrence generation.

The minimum test set should include an ordinary winter reading and an ordinary summer reading, the missing March reading, both explicit November choices, the November reading with no choice, an invalid zone key, an already-aware input, and an invalid policy. Also reject occurrence selectors on ordinary readings, nonzero input fold values, and years outside the declared range. A missing zone belongs at whichever interface enforces its presence. Test it there rather than allowing an accidental downstream exception to become the public contract.

Write assertions against the result’s UTC identity and intended error behavior. A string that looks correct is weaker evidence than a result with the expected representation and value. For repeated readings, assert the two expected UTC instants separately and also assert that they differ by one hour in this historical example. That extra relationship helps make an accidental duplicate visible.

Separate test fixtures from the implementation under test. A helper that computes every expected result with the same candidate logic can reproduce the same bug on both sides of an assertion. Use manually established expected UTC values for the central cases, then add independently designed properties for broader coverage.

What actually ran: 57 distinct named unittest cases passed with no failures or skips on CPython 3.12.14 using system time-zone data identified as 2026b. The same 57 cases passed in a fresh process forced to the already installed tzdata 2026.3 package, which reports IANA version 2026c. That is 57 tests run twice, not 114 different scenarios. The suite contains 31 literal-fixture tests, 20 contract and behavior tests, and six calendar-versus-elapsed tests.

The checks cover the historical New York examples, half-hour transitions on Australia/Lord_Howe, selected non-DST dates in Asia/Kolkata, transition boundaries down to a microsecond, and the deliberate input restrictions. A separate 28-test review also passed, including an independently implemented UTC-to-local scanning check. These are finite local behavior checks, not a model-quality benchmark, exhaustive proof, or production certification. No DeepSeek request was made.

Save the two expanded files below into one directory. Run python time_logic.py for the demonstration, then python -m unittest -v test_time_logic for the tests. The Python code imports only the standard library, but zoneinfo still needs installed IANA rule data from the operating system or the optional tzdata package. Missing data remains an error. Python 3.10 grammar was checked; only the recorded 3.12.14 runtime was executed.

Show time_logic.py: complete runnable example
"""Bounded, offline Python 3.10+ time-zone teaching example.

The runtime must have IANA zone data. See README.md for the exact contract.
"""

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

UTC = timezone.utc  # datetime.UTC requires Python 3.11; this also works on 3.10.
MIN_YEAR, MAX_YEAR = 1970, 2099


class NonexistentTimeError(ValueError):
    """The requested wall time falls in a clock-forward gap."""


class AmbiguousTimeError(ValueError):
    """The requested wall time needs an explicit occurrence."""


def valid_utc_instants(wall: datetime, zone_key: str) -> tuple[datetime, ...]:
    """Return zero, one, or two distinct UTC instants, in chronological order."""
    if type(wall) is not datetime or wall.tzinfo is not None:
        raise TypeError("wall must be a built-in datetime with tzinfo=None")
    if wall.fold != 0:
        raise ValueError("wall.fold must be 0; use occurrence to choose a fold")
    if not MIN_YEAR <= wall.year <= MAX_YEAR:
        raise ValueError(f"wall year must be {MIN_YEAR}..{MAX_YEAR}")
    if not isinstance(zone_key, str):
        raise TypeError("zone_key must be an IANA key string")
    if not zone_key:
        raise ValueError("zone_key must not be empty")
    zone = ZoneInfo(zone_key)  # Missing data/key: propagate ZoneInfoNotFoundError.
    instants = set()
    for fold in (0, 1):
        # Attaching tzinfo creates a hypothesis; it does NOT validate wall.
        candidate = wall.replace(tzinfo=zone, fold=fold)
        instant = candidate.astimezone(UTC)
        restored = instant.astimezone(zone)
        if restored.replace(tzinfo=None, fold=0) == wall:
            instants.add(instant)  # Compare/deduplicate UTC, never local datetimes.
    return tuple(sorted(instants))


def classify_local(wall: datetime, zone_key: str) -> str:
    """Return 'gap', 'unique', or 'fold'; input errors still raise."""
    return ("gap", "unique", "fold")[len(valid_utc_instants(wall, zone_key))]


def resolve_local(
    wall: datetime, zone_key: str, occurrence: str | None = None
) -> datetime:
    """Resolve a wall time; never silently shift a gap or choose a fold."""
    if occurrence not in (None, "earlier", "later"):
        raise ValueError("occurrence must be None, 'earlier', or 'later'")
    instants = valid_utc_instants(wall, zone_key)
    if not instants:
        raise NonexistentTimeError(f"{wall.isoformat()} does not exist in {zone_key}")
    if len(instants) == 2 and occurrence is None:
        raise AmbiguousTimeError("choose occurrence='earlier' or 'later'")
    if len(instants) == 1 and occurrence is not None:
        raise ValueError("occurrence is only allowed for an ambiguous wall time")
    instant = instants[-1] if occurrence == "later" else instants[0]
    return instant.astimezone(ZoneInfo(zone_key))


def demo() -> None:
    """Historical demonstrations; no network calls or model calls."""
    ny = "America/New_York"
    for wall in (datetime(2024, 3, 10, 2, 30), datetime(2024, 11, 3, 1, 30)):
        print(f"{ny} {wall.isoformat()} -> {classify_local(wall, ny)}")
        try:
            resolve_local(wall, ny)
        except (NonexistentTimeError, AmbiguousTimeError) as exc:
            print(f"  {type(exc).__name__}: {exc}")
    wall = datetime(2024, 11, 3, 1, 30)
    for occurrence in ("earlier", "later"):
        local = resolve_local(wall, ny, occurrence)
        print(f"  {occurrence}: {local.isoformat()} -> {local.astimezone(UTC).isoformat()}")

    print("\nElapsed 24 hours versus next local date at the same clock time:")
    for start_wall in (datetime(2024, 3, 9, 12), datetime(2024, 11, 2, 12)):
        start = resolve_local(start_wall, ny)
        start_utc = start.astimezone(UTC)
        elapsed_24 = (start_utc + timedelta(hours=24)).astimezone(ZoneInfo(ny))
        next_wall = start_wall + timedelta(days=1)
        next_local = resolve_local(next_wall, ny)  # Revalidate the target wall time.
        elapsed_hours = (next_local.astimezone(UTC) - start_utc).total_seconds() / 3600
        print(f"  start: {start.isoformat()}")
        print(f"  +24 elapsed hours: {elapsed_24.isoformat()}")
        print(f"  next local date:  {next_local.isoformat()} ({elapsed_hours:g} elapsed hours)")

    lh = "Australia/Lord_Howe"
    wall = datetime(2024, 4, 7, 1, 45)
    print(f"\n{lh} {wall.isoformat()} -> {classify_local(wall, lh)}")
    for instant in valid_utc_instants(wall, lh):
        print(f"  {instant.isoformat()}")
    wall = datetime(2024, 11, 3, 1, 30)
    print(f"Asia/Kolkata {wall.isoformat()} -> {classify_local(wall, 'Asia/Kolkata')}")


if __name__ == "__main__":
    demo()
Show test_time_logic.py: complete offline test suite
"""Offline tests with literal UTC expectations derived independently of the resolver.

Expected values are not computed by the implementation under test. See sources.md.
Every fixture becomes a separately named unittest, so counts are reproducible.
"""

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

from time_logic import (
    UTC, AmbiguousTimeError, NonexistentTimeError,
    classify_local, resolve_local, valid_utc_instants,
)

NY = "America/New_York"
LH = "Australia/Lord_Howe"
IN = "Asia/Kolkata"

# name, IANA key, wall ISO string, literal expected UTC ISO string(s).
CASES = [
    ("ny_winter", NY, "2024-01-15T12:00:00", ("2024-01-15T17:00:00+00:00",)),
    ("ny_summer", NY, "2024-07-15T12:00:00", ("2024-07-15T16:00:00+00:00",)),
    ("ny_before_gap", NY, "2024-03-10T01:59:59.999999", ("2024-03-10T06:59:59.999999+00:00",)),
    ("ny_gap_start", NY, "2024-03-10T02:00:00", ()),
    ("ny_gap_middle", NY, "2024-03-10T02:30:00", ()),
    ("ny_gap_end_exclusive_minus_tick", NY, "2024-03-10T02:59:59.999999", ()),
    ("ny_after_gap", NY, "2024-03-10T03:00:00", ("2024-03-10T07:00:00+00:00",)),
    ("ny_before_fold", NY, "2024-11-03T00:59:59.999999", ("2024-11-03T04:59:59.999999+00:00",)),
    ("ny_fold_start", NY, "2024-11-03T01:00:00", ("2024-11-03T05:00:00+00:00", "2024-11-03T06:00:00+00:00")),
    ("ny_fold_middle", NY, "2024-11-03T01:30:00", ("2024-11-03T05:30:00+00:00", "2024-11-03T06:30:00+00:00")),
    ("ny_fold_last_tick", NY, "2024-11-03T01:59:59.999999", ("2024-11-03T05:59:59.999999+00:00", "2024-11-03T06:59:59.999999+00:00")),
    ("ny_after_fold", NY, "2024-11-03T02:00:00", ("2024-11-03T07:00:00+00:00",)),
    ("lh_before_fold", LH, "2024-04-07T01:29:59.999999", ("2024-04-06T14:29:59.999999+00:00",)),
    ("lh_fold_start", LH, "2024-04-07T01:30:00", ("2024-04-06T14:30:00+00:00", "2024-04-06T15:00:00+00:00")),
    ("lh_fold_middle", LH, "2024-04-07T01:45:00", ("2024-04-06T14:45:00+00:00", "2024-04-06T15:15:00+00:00")),
    ("lh_fold_last_tick", LH, "2024-04-07T01:59:59.999999", ("2024-04-06T14:59:59.999999+00:00", "2024-04-06T15:29:59.999999+00:00")),
    ("lh_after_fold", LH, "2024-04-07T02:00:00", ("2024-04-06T15:30:00+00:00",)),
    ("lh_before_gap", LH, "2024-10-06T01:59:59.999999", ("2024-10-05T15:29:59.999999+00:00",)),
    ("lh_gap_start", LH, "2024-10-06T02:00:00", ()),
    ("lh_gap_middle", LH, "2024-10-06T02:15:00", ()),
    ("lh_gap_last_tick", LH, "2024-10-06T02:29:59.999999", ()),
    ("lh_after_gap", LH, "2024-10-06T02:30:00", ("2024-10-05T15:30:00+00:00",)),
    ("kolkata_winter", IN, "2024-01-15T12:00:00", ("2024-01-15T06:30:00+00:00",)),
    ("kolkata_no_us_gap", IN, "2024-03-10T02:30:00", ("2024-03-09T21:00:00+00:00",)),
    ("kolkata_no_us_fold", IN, "2024-11-03T01:30:00", ("2024-11-02T20:00:00+00:00",)),
    ("kolkata_microseconds", IN, "2024-07-15T12:34:56.123456", ("2024-07-15T07:04:56.123456+00:00",)),
    ("utc_lower_bound", "Etc/UTC", "1970-01-01T00:00:00", ("1970-01-01T00:00:00+00:00",)),
    ("utc_upper_bound", "Etc/UTC", "2099-12-31T23:59:59.999999", ("2099-12-31T23:59:59.999999+00:00",)),
    ("ny_lower_bound_utc_crossing", NY, "1970-01-01T00:00:00", ("1970-01-01T05:00:00+00:00",)),
    ("kolkata_lower_bound_utc_previous_year", IN, "1970-01-01T00:00:00", ("1969-12-31T18:30:00+00:00",)),
    ("ny_upper_bound_utc_next_year", NY, "2099-12-31T23:59:59.999999", ("2100-01-01T04:59:59.999999+00:00",)),
]


class LiteralFixtureTests(unittest.TestCase):
    pass


def fixture_test(zone, wall_text, expected_texts):
    def test(self):
        wall = datetime.fromisoformat(wall_text)
        expected = tuple(datetime.fromisoformat(text) for text in expected_texts)
        self.assertEqual(valid_utc_instants(wall, zone), expected)
        self.assertEqual(classify_local(wall, zone), ("gap", "unique", "fold")[len(expected)])
        if not expected:
            # No fold selector may silently repair a gap.
            for occurrence in (None, "earlier", "later"):
                with self.assertRaises(NonexistentTimeError):
                    resolve_local(wall, zone, occurrence)
        elif len(expected) == 1:
            local = resolve_local(wall, zone)
            self.assertEqual(local.astimezone(UTC), expected[0])
            self.assertEqual(local.replace(tzinfo=None), wall)
            self.assertEqual(local.fold, 0)
        else:
            with self.assertRaises(AmbiguousTimeError):
                resolve_local(wall, zone)
            for occurrence, fold, instant in zip(("earlier", "later"), (0, 1), expected):
                local = resolve_local(wall, zone, occurrence)
                self.assertEqual(local.astimezone(UTC), instant)
                self.assertEqual(local.replace(tzinfo=None, fold=0), wall)
                self.assertEqual(local.fold, fold)
    return test


for name, zone, wall, expected in CASES:
    setattr(LiteralFixtureTests, "test_" + name, fixture_test(zone, wall, expected))


class ContractTests(unittest.TestCase):
    def test_unknown_key(self):
        with self.assertRaises(ZoneInfoNotFoundError):
            resolve_local(datetime(2024, 1, 1), "Example/Definitely_Not_A_Zone")

    def test_aware_input_rejected(self):
        with self.assertRaises(TypeError):
            resolve_local(datetime(2024, 1, 1, tzinfo=UTC), NY)

    def test_zoned_input_rejected(self):
        with self.assertRaises(TypeError):
            resolve_local(datetime(2024, 11, 3, 1, 30, tzinfo=ZoneInfo(NY), fold=1), NY)

    def test_tzinfo_with_none_offset_rejected(self):
        class NoneOffset(tzinfo):
            def utcoffset(self, value):
                return None
        # Technically naive to datetime, but outside this stricter API contract.
        with self.assertRaises(TypeError):
            resolve_local(datetime(2024, 1, 1, tzinfo=NoneOffset()), NY)

    def test_date_is_not_datetime(self):
        with self.assertRaises(TypeError):
            resolve_local(date(2024, 1, 1), NY)

    def test_string_is_not_datetime(self):
        with self.assertRaises(TypeError):
            resolve_local("2024-01-01T00:00:00", NY)

    def test_datetime_subclass_is_outside_contract(self):
        class CustomDatetime(datetime):
            pass
        with self.assertRaises(TypeError):
            resolve_local(CustomDatetime(2024, 1, 1), NY)

    def test_nonstring_zone_rejected(self):
        with self.assertRaises(TypeError):
            resolve_local(datetime(2024, 1, 1), ZoneInfo(NY))

    def test_empty_zone_rejected(self):
        with self.assertRaises(ValueError):
            resolve_local(datetime(2024, 1, 1), "")

    def test_absolute_zone_path_rejected(self):
        with self.assertRaises(ValueError):
            resolve_local(datetime(2024, 1, 1), "/usr/share/zoneinfo/America/New_York")

    def test_naive_fold_flag_rejected(self):
        with self.assertRaises(ValueError):
            resolve_local(datetime(2024, 11, 3, 1, 30, fold=1), NY, "later")

    def test_below_lower_bound_rejected(self):
        with self.assertRaises(ValueError):
            resolve_local(datetime(1969, 12, 31, 23, 59, 59, 999999), "Etc/UTC")

    def test_above_upper_bound_rejected(self):
        with self.assertRaises(ValueError):
            resolve_local(datetime(2100, 1, 1), "Etc/UTC")

    def test_invalid_occurrence_rejected(self):
        for choice in ("first", "LATER", "", 0, False, [], {}):
            with self.subTest(choice=choice), self.assertRaises(ValueError):
                resolve_local(datetime(2024, 11, 3, 1, 30), NY, choice)

    def test_occurrence_on_unique_time_rejected(self):
        for choice in ("earlier", "later"):
            with self.subTest(choice=choice), self.assertRaises(ValueError):
                resolve_local(datetime(2024, 1, 1), NY, choice)

    def test_same_zone_equality_is_not_instant_equality(self):
        wall = datetime(2024, 11, 3, 1, 30)
        earlier = resolve_local(wall, NY, "earlier")
        later = resolve_local(wall, NY, "later")
        self.assertEqual(earlier, later)  # Python deliberately ignores fold here.
        self.assertEqual(later - earlier, timedelta(0))
        self.assertNotEqual(earlier.astimezone(UTC), later.astimezone(UTC))
        self.assertEqual(later.astimezone(UTC) - earlier.astimezone(UTC), timedelta(hours=1))
        self.assertEqual(len(valid_utc_instants(wall, NY)), 2)

    def test_unique_fold_hypotheses_deduplicate(self):
        self.assertEqual(len(valid_utc_instants(datetime(2024, 1, 15, 12), NY)), 1)

    def test_lord_howe_fold_is_thirty_minutes(self):
        earlier, later = valid_utc_instants(datetime(2024, 4, 7, 1, 45), LH)
        self.assertEqual(later - earlier, timedelta(minutes=30))

    def test_attaching_tzinfo_does_not_validate_gap(self):
        wall = datetime(2024, 3, 10, 2, 30)
        attached = wall.replace(tzinfo=ZoneInfo(NY))
        self.assertEqual(attached.hour, 2)
        self.assertEqual(attached.utcoffset(), timedelta(hours=-5))
        self.assertEqual(valid_utc_instants(wall, NY), ())

    def test_python_mixed_naive_aware_subtraction_rejected(self):
        with self.assertRaises(TypeError):
            _ = datetime(2024, 1, 1, tzinfo=timezone.utc) - datetime(2024, 1, 1)


class CalendarVersusElapsedTests(unittest.TestCase):
    def assert_day_difference(self, wall, elapsed_local_text, next_utc_text, hours):
        start = resolve_local(wall, NY)
        elapsed = (start.astimezone(UTC) + timedelta(hours=24)).astimezone(ZoneInfo(NY))
        self.assertEqual(elapsed.isoformat(), elapsed_local_text)
        next_local = resolve_local(wall + timedelta(days=1), NY)
        self.assertEqual(next_local.astimezone(UTC).isoformat(), next_utc_text)
        self.assertEqual((next_local.astimezone(UTC) - start.astimezone(UTC)).total_seconds(), hours * 3600)
        self.assertEqual(next_local - start, timedelta(days=1))  # Wall arithmetic trap.

    def test_spring_day_is_twenty_three_elapsed_hours(self):
        self.assert_day_difference(datetime(2024, 3, 9, 12), "2024-03-10T13:00:00-04:00", "2024-03-10T16:00:00+00:00", 23)

    def test_autumn_day_is_twenty_five_elapsed_hours(self):
        self.assert_day_difference(datetime(2024, 11, 2, 12), "2024-11-03T11:00:00-05:00", "2024-11-03T17:00:00+00:00", 25)

    def test_next_local_date_can_be_gap(self):
        wall = datetime(2024, 3, 9, 2, 30)
        resolve_local(wall, NY)
        with self.assertRaises(NonexistentTimeError):
            resolve_local(wall + timedelta(days=1), NY)

    def test_next_local_date_can_require_occurrence(self):
        wall = datetime(2024, 11, 2, 1, 30)
        resolve_local(wall, NY)
        with self.assertRaises(AmbiguousTimeError):
            resolve_local(wall + timedelta(days=1), NY)
        self.assertEqual(resolve_local(wall + timedelta(days=1), NY, "later").astimezone(UTC).isoformat(), "2024-11-03T06:30:00+00:00")

    def test_kolkata_next_local_date_is_twenty_four_hours(self):
        start_wall = datetime(2024, 3, 9, 12)
        start = resolve_local(start_wall, IN)
        next_local = resolve_local(start_wall + timedelta(days=1), IN)
        self.assertEqual(next_local.astimezone(UTC).isoformat(), "2024-03-10T06:30:00+00:00")
        self.assertEqual(next_local.astimezone(UTC) - start.astimezone(UTC), timedelta(hours=24))

    def test_next_local_date_crossing_contract_bound_rejected(self):
        wall = datetime(2099, 12, 31, 12)
        resolve_local(wall, "Etc/UTC")
        with self.assertRaises(ValueError):
            resolve_local(wall + timedelta(days=1), "Etc/UTC")


if __name__ == "__main__":
    unittest.main(verbosity=2)
Show the recorded demonstration output
America/New_York 2024-03-10T02:30:00 -> gap
  NonexistentTimeError: 2024-03-10T02:30:00 does not exist in America/New_York
America/New_York 2024-11-03T01:30:00 -> fold
  AmbiguousTimeError: choose occurrence='earlier' or 'later'
  earlier: 2024-11-03T01:30:00-04:00 -> 2024-11-03T05:30:00+00:00
  later: 2024-11-03T01:30:00-05:00 -> 2024-11-03T06:30:00+00:00

Elapsed 24 hours versus next local date at the same clock time:
  start: 2024-03-09T12:00:00-05:00
  +24 elapsed hours: 2024-03-10T13:00:00-04:00
  next local date:  2024-03-10T12:00:00-04:00 (23 elapsed hours)
  start: 2024-11-02T12:00:00-04:00
  +24 elapsed hours: 2024-11-03T11:00:00-05:00
  next local date:  2024-11-03T12:00:00-05:00 (25 elapsed hours)

Australia/Lord_Howe 2024-04-07T01:45:00 -> fold
  2024-04-06T14:45:00+00:00
  2024-04-06T15:15:00+00:00
Asia/Kolkata 2024-11-03T01:30:00 -> unique

A successful local run supports the behavior tested in that environment. It does not establish that DeepSeek always produces correct time code or that an application’s entire scheduling behavior is covered. Keep the environment, command, and observed result alongside the test file so another developer can repeat the check instead of trusting a screenshot of a green result.

Keep elapsed time separate from calendar time

The March noon example deserves its own test because conversion and arithmetic can fail independently. For an elapsed requirement, resolve the starting instant, perform the duration arithmetic in UTC, and only then convert the result for display. For a next-local-day requirement, generate the next local calendar reading and pass it through the local resolver. This keeps the two meanings visible at the call site.

Python documents a subtle behavior here: subtraction between aware datetimes with the same tzinfo object ignores that zone information. Addition of a timedelta likewise does not perform time-zone adjustments. Therefore, direct subtraction of two local datetimes is not a reliable expression of elapsed time across an offset change. Convert the operands to UTC when elapsed difference is the requirement. [1]

With the same New York zone object, subtracting local noon on March 9 from local noon on March 10 yields a wall-calendar difference of one day. The corresponding UTC readings are 17:00 on March 9 and 16:00 on March 10, whose elapsed difference is twenty-three hours. Label both expectations in the test. Calling one of them “wrong” without naming the intended meaning hides the actual defect.

A process timeout introduces another distinction. Python’s monotonic clock supports measuring intervals without following system-clock adjustments; its reference point is undefined, so use differences between readings rather than treating a reading as a calendar timestamp. [5] In a retry loop, that can be a better fit than repeatedly subtracting wall-clock timestamps. Persistence across restarts needs a separate design rather than storing a monotonic reading as a universal deadline.

Ask DeepSeek to name each arithmetic operation in ordinary language. “Advance the calendar date while preserving local noon” and “advance the instant by twenty-four hours” should lead to different code paths. A helper named add_day encourages confusion; two deliberately named operations are easier to review, test, and explain to someone investigating a reminder complaint.

Starting at New York noon on March 9, 2024, adding 24 elapsed hours reaches 13:00 the next day. Keeping local noon on March 10 is only 23 elapsed hours later.
Elapsed addition and calendar recurrence answer different questions. Resolve a local recurrence separately for each intended date.

Test boundaries and information loss

After the central examples pass, widen the test space along one dimension at a time. Check valid readings immediately before and after the chosen transition boundary. Include minute, second, and microsecond fields if the interface promises to preserve them. Then try an ordinary zone and date with a non-whole-hour offset so a hidden assumption about whole hours becomes easier to spot.

Choose those additional cases from the zones your application actually supports and verify their expected values independently. Do not ask the model for a long unverified list and treat its fluency as evidence. A small test with a documented reason is more maintainable than dozens of dates whose inclusion nobody understands.

Useful properties complement explicit examples. A successful result should convert back to the requested local fields in the named zone. Selecting earlier should never produce a later UTC candidate than selecting later for the same ambiguous input. Repeating the same call with identical inputs and the same zone data should preserve the result. Each property must describe the approved domain, including any intentional rejections.

Then inspect the boundaries outside Python. Serialize a resolved instant, store it through the actual application adapter, read it back, and confirm its identity. Separately preserve a zone key when future local intent matters. A database adapter that discards an offset, or a form that drops the zone field, can undo a correct resolver without changing the resolver’s unit-test result.

Watch date-only values during this integration check. An attendance date should not drift to the preceding or following day because a presentation layer manufactured midnight and applied a viewer’s zone. Write an assertion about the date the user selected. This checks a business meaning directly and avoids making a timestamp convention carry information it was never designed to represent.

Investigate failures without changing policy

When a case fails, give DeepSeek the smallest reproducer that retains the problem: the approved contract, candidate function, single failing input, expected outcome, observed outcome, and environment details. Include an actual traceback if one exists. Remove account identifiers and unrelated production data. A small case makes it easier to inspect whether the problem concerns parsing, candidate validation, representation, or arithmetic.

Prompt 3: Failure analysis with policy preserved

Analyze the supplied failing case against the approved contract. The expected result is fixed unless I explicitly approve a policy change. First identify the earliest step where the observed behavior diverges from that contract. Distinguish a likely implementation defect, an environment or time-zone-data issue, and an unresolved requirement.

Propose the smallest patch that preserves our policies and name the existing test that demonstrates the repair. Suggest one additional regression case if it exercises a different failure mode. Do not normalize a gap, pick a fold, infer a zone, edit an expected value, or catch every exception merely to make the run green. If the contract is genuinely insufficient, ask the specific question and stop before choosing its answer.

Evaluate the proposed explanation against the executed trace. A polished narrative is still a hypothesis until it matches the failure. If the model says an offset is wrong, inspect the value and the zone-data environment. If it blames the parser, provide the already-parsed input to the resolver directly. These small isolation steps reduce the chance of accepting a broad rewrite for a narrow defect.

Retain the original failing case after the fix. The regression-testing workflow is useful for organizing the evidence, but the specific lesson here is to preserve the time meaning the bug violated. Name a regression for the behavior, such as rejecting a nonexistent local booking, rather than for the date on which someone noticed it.

Review generated time code for hidden policy

During review, focus first on places where missing information becomes a default. Look for calls that obtain the host’s local zone, branches that catch an unavailable-zone error and substitute UTC, or code that removes an attached offset to satisfy an input type. Those choices can make a function convenient while changing which instant the user intended.

Next, inspect representation changes. Python’s replace(tzinfo=...) changes the attached zone information without converting the clock fields, while astimezone(...) converts a datetime to represent the same instant in another zone. [1] In the teaching resolver, attaching a zone is deliberately used to construct a candidate. Elsewhere, a similar line may accidentally relabel an already-known instant. Review its purpose in context.

Check comparisons as well as arithmetic. With the same tzinfo object, Python compares repeated local readings without using fold; normalize to UTC for a comparison intended to distinguish their instants. [1, 3] The candidate set therefore uses UTC identity. Error handling should also retain useful categories. If every problem becomes “invalid date,” an operator cannot tell whether the user selected a gap, a deployment lacks zone data, or a developer supplied the wrong input type.

Use the code-review guide for the broader review process, while keeping this review tied to a few specific questions: Which meaning enters this line? Which meaning leaves it? Was information discarded? Who approved the default? Which independent assertion would fail if this interpretation were wrong?

Finally, review the tests as code. Confirm they call the public interface, preserve their expected values, and do not skip the hard cases after an exception. A test named for a gap that merely asserts “an object was returned” protects the opposite of this tutorial’s contract. Review names, assertions, and policy language together.

Record the time-zone data environment

Time-zone rules are data dependencies. IANA maintains the database as civil-time rules change. Python’s zoneinfo uses system zone data or the first-party tzdata package, and a missing data source can make a zone unavailable. A package pin alone does not prove which source a process actually loaded. [2, 4]

For a reproducible review, record the Python version, operating environment, zone key, data-source configuration, and available database or package version information. If you cannot determine the active data version, state that limitation. Do not fill the gap with a plausible version copied from an unrelated container or from a package that the process might never use.

Separate two questions when an upgrade changes an outcome. Did the conversion algorithm regress, or did the rule data change the intended interpretation? Preserve the old and new results, the input, and the relevant environment details. Then ask the responsible owner whether existing future appointments should retain their previously resolved instants or be recalculated from their local intentions.

That is a product migration decision. For a fictional conference booking, keeping the advertised local start may matter more than retaining an old UTC conversion. For an already-recorded audit event, changing its instant would destroy the meaning of the record. Store enough information to distinguish these cases rather than applying one blanket migration to every time-related field.

Use historical fixtures to protect the algorithm, and maintain a separate review process for future schedules affected by data updates. Neither should silently rewrite the other. When asking DeepSeek about a discrepancy, provide both environments and the exact rule-data evidence you have, and require it to label unsupported explanations as hypotheses.

Apply the method to product decisions

Consider a fictional equipment-rental app with a “return tomorrow at the same time” button. A product owner may mean the same local clock reading on the next calendar day. An engineering shortcut may instead add twenty-four hours to an instant. Present the March noon example to the owner: should the displayed return time be noon or 13:00? Their answer chooses the contract; a model should not choose it on their behalf.

A fictional class-booking app has another problem when a user selects a repeated 01:30 slot. The backend can identify both instants, but the interface still needs to communicate the choice. Show the two alternatives in language the intended audience can understand, including the date, zone, and distinguishing offset where useful. Ensure the confirmation preserves the selected occurrence rather than reconstructing it later from identical clock fields.

A daily report introduces recurrence. The team may want one report for each local business date, even when the elapsed spacing varies. The small resolver can help validate an individual occurrence, but it does not determine holiday rules, missed-run behavior, duplicate prevention, or delivery guarantees. Keep those open questions explicit instead of extending a short conversion helper into an unreviewed scheduling framework.

Use these scenarios as conversation tools, not universal answers. Financial, employment, healthcare, and other regulated deadlines may depend on rules beyond this tutorial, so obtain the relevant domain guidance. The fictional examples establish no legal interpretation. The useful engineering habit is to make a consequential choice visible before it becomes an arithmetic operation.

Prepare a reviewable change

A good handoff includes the contract, the small implementation, the independent fixtures, the observed test command and result, and the environment notes. Keep the actual DeepSeek prompt and response if you used them, subject to your team’s retention and privacy rules. Distinguish the model’s suggested explanation from statements you verified by running the code or checking primary documentation.

  • Confirm the boundary. The function accepts the documented input meaning and returns the documented output meaning. Parsing, defaults, recurrence, storage, and execution timing remain separately specified where the application needs them.
  • Confirm policy ownership. Gaps, folds, missing zones, unsupported policies, and future rule-data changes have an approved behavior or a visible unresolved question. No repair has quietly changed those choices.
  • Confirm independent evidence. The central historical fixtures use fixed expected outcomes. The elapsed-versus-local-day distinction is exercised directly. Integration checks protect information that crosses storage and presentation boundaries.
  • Confirm operational visibility. Failures retain enough context to diagnose the category without exposing unnecessary personal data. The deployment’s time-zone data source is understood or its uncertainty is recorded.

Set a stopping condition for the work. For this tutorial’s component, completion means the agreed cases and boundary checks pass in the target environment and a reviewer can explain the exceptional policies. It does not require solving every possible calendar problem. New requirements should produce a new contract decision and relevant tests, rather than a growing collection of special cases inside the same function.

The lasting benefit of using DeepSeek here is a more inspectable engineering conversation. Ask it to surface ambiguity, propose a constrained candidate, and help localize failures. Let the contract specify intent and independently executed checks establish behavior. That division of responsibility is what makes the result useful when the next clock change arrives.

Questions that usually need a decision

Should every stored date become UTC?

Choose storage according to meaning. A resolved event instant is a good candidate for a consistent UTC representation. A date-only selection or a future recurrence needs its own information preserved. Converting everything to UTC can erase the local intention that a later edit or rule-data update needs.

Can a numeric offset replace a named zone?

For a single fully specified timestamp, an offset can establish the instant. For future local occurrences, retain the named zone as part of the instruction. Ask which question the field needs to answer before dropping either value, and define how conflicting supplied values will be handled.

Should missing local times move forward automatically?

Only if the product contract says so and defines the destination precisely. Moving to the first valid reading and preserving the requested minute by shifting an hour are different behaviors. This tutorial rejects gaps so the choice remains visible; another application must test its approved alternative.

Does a passing test suite make generated code safe to deploy?

It supplies evidence for the tested contract and environment. Review integration behavior, error handling, supported input ranges, and operational requirements before deployment. A model response or a local unit-test result alone cannot establish how the surrounding application stores, displays, or acts on the resolved instant.

Sources & References

Primary documentation checked October 4, 2026. The workflow, prompts, fictional scenarios, and review recommendations are original tutorial material. Numbered references identify the library and format rules used in the explanation.

  1. Python datetime documentation — arithmetic, comparison, and conversion semantics.
  2. Python zoneinfo documentation — named-zone behavior, data sources, and unavailable-zone errors.
  3. PEP 495: Local Time Disambiguation — folds, gaps, and validation boundaries.
  4. IANA Time Zone Database — the maintained source of civil-time rule data.
  5. Python time.monotonic documentation — interval measurement and clock behavior.
  6. RFC 3339: Date and Time on the Internet — timestamp representation and numeric offsets.
  7. IANA 2024a North America: New York rule file: stable historical reference for the tutorial fixtures.
  8. IANA 2024a Australasia: Lord Howe rule file: stable historical reference for the tutorial fixtures.
  9. IANA 2024a Asia: Kolkata rule file: stable historical reference for the tutorial fixtures.
Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *