Dates, durations and timezone-aware time
Separate elapsed time, calendar dates and local-clock interpretation.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Explain a timestamp needs context
- Apply arithmetic depends on intent
- Reason about test time as a dependency
A timestamp needs context
A date names a calendar day. A datetime names a clock reading, and an aware datetime also carries an offset interpretation that lets you compare instants.
Understand first
Two offices can record the same event with different clock readings. Comparing bare clock numbers loses the offset that connects them. Begin with integers and object method calls; no host timezone setup is needed for these fixtures.
Words you will see
- Instant
- One point on the time line.
- Aware datetime
- A datetime whose timezone supplies a usable UTC offset.
- Fixed offset
- A constant difference from UTC, without seasonal regional rules.
Change the reading without moving the event
utc explicitly identifies 08:00 at offset zero. timezone constructs a fixed +05:30 offset. astimezone computes 13:30 with that offset, preserving the instant. Equality is True even though the displayed hours differ.
The name local here means a chosen display offset, not the laptop's settings. Every conversion target is explicit. Calling astimezone without a target would consult environment defaults and is intentionally avoided in this deterministic lesson.
Do not invent an offset for an unknown reading
A naive datetime lacks an offset interpretation. Attaching tzinfo with replace labels the reading; it does not perform an instant-preserving conversion. Only attach it when a contract already defines the reading's timezone. Mixed aware/naive ordering and subtraction raise TypeError.
Use date for a birthday or due day with no time of day. Use an aware datetime for an event instant. A fixed offset does not describe a region's historical daylight-saving rules; real regional scheduling needs named-zone data and an explicit ambiguous-time policy.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
utc = datetime(2026, 1, 1, 8, tzinfo=timezone.utc)Construct a known instant, not the current clock.
offset = timezone(timedelta(hours=5, minutes=30))Choose a fixed display offset.
local = utc.astimezone(offset)Convert the clock reading while retaining the instant.
print(local == utc)Confirm the two aware values identify the same instant.
A naive datetime has no timezone interpretation attached. An aware datetime identifies a timezone/offset. Store event instants consistently, commonly in UTC, while retaining the user's scheduling timezone when the meaning is a local calendar rule.
Conceptual instant conversion; fixed offsets are not regional DST rules
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- UTC reading08:00 at +00:00 identifies one instant.
- Offset conversionAdd five hours thirty minutes to the display clock.
- Same instant13:30 at +05:30 compares equal to the UTC reading.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Cross midnight.
Try: Change the UTC constructor's hour from 8 to 22.
The converted date becomes January 2 at 03:30; equality stays True.
Use a negative offset.
Try: Set offset = timezone(timedelta(hours=-3)).
The original 08:00 UTC becomes 05:00-03:00 without consulting the host.
Before you move on
What is 23:30 UTC on January 1 at fixed offset +02:00?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
01:30 on January 2. Conversion can cross a calendar-day boundary while still representing exactly the same instant.
Arithmetic depends on intent
A duration measures an amount of time. Calendar arithmetic moves dates, while elapsed-time arithmetic must preserve the intended instant and clock assumptions.
Understand first
A due day and a retry timeout ask different questions. A due day belongs to a calendar. A timeout counts elapsed time. timedelta represents a duration, but the meaning of adding it depends on the date/time objects involved.
Words you will see
- timedelta
- A duration stored with days, seconds and microseconds.
- Calendar boundary
- A change of day, month or year handled by calendar rules.
- total_seconds
- The whole duration expressed in seconds, including its days and sign.
Let the calendar handle rollover
Adding one day to January 31 produces February 1; you do not manually increment the day field to an invalid January 32. The datetime fixture begins at 23:30 UTC. Adding two hours crosses midnight and produces 01:30 on the next day.
Subtracting end and start creates a timedelta. total_seconds returns 7200. The seconds attribute alone is only one normalised component; it omits whole days and can mislead for negative intervals. int is safe here because this fixture has no fractional seconds.
State which clock the question needs
Across a regional daylight-saving transition, tomorrow at the same local hour need not be twenty-four elapsed hours later. Convert event instants to UTC for elapsed comparisons. Keep a region and an ambiguity policy for repeated local-calendar appointments.
For a live deadline use time.monotonic, whose readings are intended for elapsed differences rather than calendar display. This example does not call any current clock or sleep. Fixed UTC fixtures make both output and boundary reasoning independent of machine location.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
day = date(2026, 1, 31)Represent a calendar day without a time or offset.
print(day + timedelta(days=1))Let date arithmetic cross to February.
end = start + timedelta(hours=2)Move the explicit UTC instant by two hours.
print(int((end - start).total_seconds()))Display the complete interval, 7200 seconds.
A duration of 24 hours is not always the same as 'tomorrow at 09:00' across daylight-saving changes. Use date arithmetic for calendar dates and timezone-aware conversions for instants. Use time.monotonic for elapsed deadlines, not a wall clock that can jump.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Reverse the interval.
Try: Print int((start - end).total_seconds()) instead.
The duration becomes -7200.
Include a whole extra day.
Try: Change timedelta(hours=2) to timedelta(days=1, hours=2).
The total becomes 93600 seconds, not just 7200.
Before you move on
What is the total number of seconds in timedelta(days=1, minutes=2)?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
86520: one day contributes 86400 and two minutes add 120. Reading only seconds would incorrectly give 120.
Convert and compare instants
Subtracting two explicit UTC datetimes gives their elapsed duration. This is a safe small model for event timing when both operands describe known instants.
Understand first
A processing report may need a stable timestamp and an elapsed total. The original ninety-minute program shows both without a wall clock or regional database. Read timedelta construction and timezone awareness before treating the subtraction as an elapsed-time claim.
Words you will see
- ISO format
- A structured date/time spelling that can include the UTC offset.
- UTC
- A shared zero-offset reference for event instants.
- Elapsed interval
- The duration between two events rather than their displayed hour difference alone.
Follow the original ninety minutes
start is January 1 at 08:00 UTC. Adding timedelta(minutes=90) makes end 09:30 UTC. isoformat includes +00:00 so a reader can see the offset instead of guessing it from the hour.
end minus start is one hour and thirty minutes. total_seconds translates that duration to 5400 seconds. Nothing measures the speed of the script, and no printed value depends on how long the learner waits before pressing Run.
Do not broaden this guarantee silently
This is explicit UTC arithmetic. For regional aware values around offset transitions, first decide whether the task means wall-clock scheduling or elapsed instants. Normalise to UTC for elapsed subtraction; preserving local calendar rules is a separate task.
A naive incoming value is not made trustworthy by guessing the machine timezone. Reject it or require a documented interpretation. An actual runtime deadline should use a monotonic clock, not compare calendar timestamps that a clock correction can move.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
start = datetime(2026, 1, 1, 8, 0, tzinfo=timezone.utc)Fix both the starting reading and its UTC interpretation.
end = start + timedelta(minutes=90)Advance exactly ninety minutes in this UTC model.
print(end.isoformat())Display the end instant including +00:00.
print(int((end - start).total_seconds()))Display 5400 seconds, not 90 minutes.
The example uses a fixed UTC instant rather than the current clock, keeping its output reproducible. Both operands share an explicit timezone interpretation.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Cross the date boundary.
Try: Use timedelta(minutes=1000) instead of 90.
The end becomes January 2 at 00:40 UTC and the total is 60000.
Show a negative duration.
Try: Change the subtraction to start - end.
The original fixture prints -5400 as its final line.
Before you move on
If the original duration becomes 125 minutes, what are the end reading and total seconds?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
10:05 UTC and 7500 seconds. The offset remains +00:00 because the arithmetic stays in UTC.
Where this idea earns its place
Calendar dates, wall-clock times and elapsed durations answer different questions. A deadline of ninety minutes from now is not the same kind of rule as every weekday at 09:00 in a named region. Choose the intended semantics before selecting datetime operations, otherwise daylight-saving transitions can turn apparently correct arithmetic into scheduling defects.
Follow the mechanism step by step
An aware datetime carries an offset/timezone interpretation; a naive value does not. Converting an aware instant to another timezone preserves the instant while changing its local representation. Attaching timezone information to an existing naive value can instead assert an interpretation, which is not the same operation as conversion.
Work through a concrete application
For a study reminder, store the user's local recurrence rule and named timezone, then derive each delivery instant using an explicit ambiguity policy. For an already-recorded event, store an unambiguous instant and format it for the viewer. For measuring a timeout, use a monotonic clock rather than comparing wall-clock timestamps.
Failure cases and misleading shortcuts
A fixed offset does not encode a region's future DST rules. Some local times repeat and others do not exist. Parsing a timestamp and discarding its offset loses information; comparing naive and aware values can fail or encourage incorrect coercion. Sleep-based tests also become slow and flaky when they substitute waiting for a controllable clock.
Cost, ownership and alternatives
Time conversion may depend on available timezone data and the runtime environment. Persist enough meaning to recompute schedules after rule updates, and keep the original user intent distinct from a derived UTC instant. A database timestamp alone cannot reconstruct an unspecified recurring local-time policy.
Verify the contract
Test midnight boundaries, leap dates, DST transitions in supported zones and timezone changes. Inject a clock for deadline logic and assert behaviour without real waiting. Include malformed timestamp input and explicit units, since milliseconds versus seconds errors can be much larger than timezone mistakes.
Transfer question: A user wants tomorrow at 09:00. Should you add exactly 24 hours to today's reminder?
Not necessarily. Build the next local calendar occurrence in the user's named timezone using the documented DST policy, then convert it to an instant. Adding an elapsed duration answers a different question and may deliver at a different local hour.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: Convert and compare instants
Without copying the worked code, reproduce its observable contract: The example uses a fixed UTC instant rather than the current clock, keeping its output reproducible. Both operands share an explicit timezone interpretation. Then change one boundary input and explain the result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guide: normalise an explicit instant
Convert an aware datetime to a stable UTC ISO string.
The contract
- Input is a datetime. Reject a naive datetime with ValueError; never infer a host timezone.
- Return a string from astimezone(timezone.utc).isoformat(), including the +00:00 suffix.
- Do not relabel the clock with replace or change the input. All tests use explicit fixed offsets.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- UTC type
from datetime import datetime, timezone r = utc_text(datetime(2026, 1, 1, 8, tzinfo=timezone.utc)) assert type(r) is str and r == '2026-01-01T08:00:00+00:00'
- positive offset
from datetime import datetime, timezone, timedelta r = utc_text(datetime(2026, 1, 1, 13, 30, tzinfo=timezone(timedelta(hours=5, minutes=30)))) assert type(r) is str and r == '2026-01-01T08:00:00+00:00'
- previous day
from datetime import datetime, timezone, timedelta r = utc_text(datetime(2026, 1, 1, 0, 30, tzinfo=timezone(timedelta(hours=2)))) assert type(r) is str and r == '2025-12-31T22:30:00+00:00'
- negative offset
from datetime import datetime, timezone, timedelta r = utc_text(datetime(2026, 1, 1, 23, tzinfo=timezone(timedelta(hours=-3)))) assert type(r) is str and r == '2026-01-02T02:00:00+00:00'
- naive rejection
from datetime import datetime, timezone r = utc_text(datetime(2026, 1, 1, tzinfo=timezone.utc)) assert type(r) is str and r.endswith('+00:00') try: utc_text(datetime(2026, 1, 1)) except ValueError: pass else: raise AssertionError('Reject naive datetime') - input preservation
from datetime import datetime, timezone, timedelta m = datetime(2026, 2, 3, 4, 5, 6, 123456, tzinfo=timezone(timedelta(hours=1))) before = m.isoformat() r = utc_text(m) assert type(r) is str and r == '2026-02-03T03:05:06.123456+00:00' assert m.isoformat() == before and utc_text(m) == r
Why reject a naive value instead of attaching UTC?
Its interpretation is unknown. Attaching UTC invents meaning. Conversion of an aware fixed-offset datetime is bounded work here and produces immutable text, without host-zone data.
Guide: compare elapsed instants
Return signed seconds between two aware instants.
The contract
- Inputs are datetimes with usable offsets. Reject either naive input with ValueError.
- Normalise both to UTC, then return a float total_seconds for end minus start; negative and fractional intervals are valid.
- Do not discard whole days or mutate inputs. No current clocks, sleeps or regional timezone database.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- ninety minutes
from datetime import datetime, timezone, timedelta s = datetime(2026, 1, 1, tzinfo=timezone.utc) r = elapsed_seconds(s, s + timedelta(minutes=90)) assert type(r) is float and r == 5400.0
- zero duration
from datetime import datetime, timezone s = datetime(2026, 1, 1, tzinfo=timezone.utc) r = elapsed_seconds(s, s) assert type(r) is float and r == 0.0
- whole days
from datetime import datetime, timezone, timedelta s = datetime(2026, 1, 1, tzinfo=timezone.utc) r = elapsed_seconds(s, s + timedelta(days=2, seconds=3)) assert type(r) is float and r == 172803.0
- negative fractions
from datetime import datetime, timezone, timedelta s = datetime(2026, 1, 1, tzinfo=timezone.utc) r = elapsed_seconds(s, s - timedelta(microseconds=500000)) assert type(r) is float and r == -0.5
- offset equivalence and ownership
from datetime import datetime, timezone, timedelta s = datetime(2026, 1, 1, 8, tzinfo=timezone.utc) e = datetime(2026, 1, 1, 10, tzinfo=timezone(timedelta(hours=2))) before = (s.isoformat(), e.isoformat()) r = elapsed_seconds(s, e) assert type(r) is float and r == 0.0 assert (s.isoformat(), e.isoformat()) == before
- reject either naive operand
from datetime import datetime, timezone s = datetime(2026, 1, 1, tzinfo=timezone.utc) r = elapsed_seconds(s, s) assert type(r) is float and r == 0.0 for pair in [(s.replace(tzinfo=None), s), (s, s.replace(tzinfo=None))]: try: elapsed_seconds(*pair) except ValueError: pass else: raise AssertionError('Reject either naive operand')
Why not use seconds or int(total_seconds())?
seconds omits whole days and normalises signs; int drops fractional precision. Explicit UTC subtraction states the elapsed-instant rule. These fixed-size datetime operations retain no mutable result.
Transfer: count by a chosen display date
Change from elapsed instants to a calendar report with an explicit display offset.
The contract
- Input is a list of aware datetimes and a fixed datetime.timezone offset. Reject any naive entry with ValueError.
- Return a fresh dict mapping ISO date strings to integer counts after conversion to the supplied offset. Preserve first-seen date order and count repeats.
- Empty input returns {}. Do not mutate/reorder the list or use the host timezone; do not reuse mutable result dictionaries.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- converted day
from datetime import datetime, timezone, timedelta r = date_counts([datetime(2026, 1, 1, 23, tzinfo=timezone.utc)], timezone(timedelta(hours=2))) assert type(r) is dict and r == {'2026-01-02': 1} assert all(type(k) is str and type(v) is int for k,v in r.items()) - empty fresh
from datetime import timezone a = date_counts([], timezone.utc) b = date_counts([], timezone.utc) assert type(a) is dict and a == {} and type(b) is dict and b == {} and a is not b - repeat counts
from datetime import datetime, timezone m = datetime(2026, 1, 1, tzinfo=timezone.utc) r = date_counts([m, m, m], timezone.utc) assert type(r) is dict and r == {'2026-01-01': 3} and type(r['2026-01-01']) is int - first-seen order and preservation
from datetime import datetime, timezone items = [datetime(2026, 1, 2, tzinfo=timezone.utc), datetime(2026, 1, 1, tzinfo=timezone.utc)] before = items[:] r = date_counts(items, timezone.utc) assert type(r) is dict and list(r.items()) == [('2026-01-02', 1), ('2026-01-01', 1)] assert items == before and all(a is b for a,b in zip(items, before)) - negative-offset rollover
from datetime import datetime, timezone, timedelta r = date_counts([datetime(2026, 1, 1, 1, tzinfo=timezone.utc)], timezone(timedelta(hours=-3))) assert type(r) is dict and r == {'2025-12-31': 1} - validation and independent results
from datetime import datetime, timezone m = datetime(2026, 1, 1, tzinfo=timezone.utc) a = date_counts([m], timezone.utc) b = date_counts([m], timezone.utc) assert type(a) is dict and type(b) is dict and a == b == {'2026-01-01': 1} and a is not b a['2026-01-01'] = 9 assert b['2026-01-01'] == 1 try: date_counts([m, m.replace(tzinfo=None)], timezone.utc) except ValueError: pass else: raise AssertionError('Reject naive entries')
Why is this not just elapsed-time arithmetic?
Grouping now depends on a specified calendar display offset. Conversion must precede date extraction. For n entries, expected dictionary work is O(n), with O(d) entries for d observed dates; result ownership is fresh.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneAmbiguous local times
Regional time rules can repeat a local reading. You need a policy for which occurrence is meant; an offset alone is not a complete regional scheduling rule.
Understand first
A clock can show the same hour twice when an offset moves backward. A reservation system cannot decide between those occurrences from the digits alone. This model supplies both offsets directly so the ambiguity can be understood in browser Python without installing timezone data.
Words you will see
- Ambiguous local time
- A wall-clock reading that can refer to more than one instant.
- Nonexistent local time
- A reading skipped when a regional clock moves forward.
- fold
- A datetime flag used by supporting timezone rules to distinguish repeated readings.
Same clock digits, different instants
first and second both display 01:30, but their offsets are -04:00 and -05:00. Converting to UTC yields 05:30 and 06:30. The second instant is an hour later even though the local hour and minute match.
These fixtures model two supplied interpretations. They do not prove that a particular region changes offset on this date. timezone builds fixed offsets; it has no transition table and does not use fold to choose a seasonal occurrence.
Use named rules only with an explicit data boundary
ZoneInfo can apply named regional rules when timezone data is available. The host may not have that database, so these browser-local examples deliberately avoid assuming it. A deployed scheduler must supply or verify its data and document the version if reproducibility matters.
Define whether an ambiguous appointment uses the earlier or later instant, and whether a nonexistent reading is rejected or shifted. Simply attaching a timezone need not validate a nonexistent local time. For elapsed intervals, convert to UTC; for recurrence, retain the regional scheduling intention.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
first = datetime(2026, 11, 1, 1, 30, tzinfo=timezone(timedelta(hours=-4)))Supply the first offset interpretation explicitly.
second = datetime(2026, 11, 1, 1, 30, tzinfo=timezone(timedelta(hours=-5)))Supply a different interpretation of the same clock digits.
print(first.astimezone(timezone.utc).isoformat())Convert the first reading to 05:30 UTC.
print(int((second - first).total_seconds()))Compare distinct fixed-offset instants and obtain 3600 seconds.
ZoneInfo supports named timezones when timezone data is available. DST transitions can repeat or skip a local time; define how your scheduler handles ambiguity and nonexistence. A fixed UTC offset is not a complete regional timezone rule.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Remove the offset difference.
Try: Give second the same -4 hour offset as first.
Both UTC displays agree and the difference becomes 0.
Reverse the comparison.
Try: Print int((first - second).total_seconds()).
The result is -3600, showing direction as well as magnitude.
Before you move on
Two records say 02:15, one at +02:00 and one at +01:00. Which instant is later?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
The +01:00 record is later: it converts to 01:15 UTC, while the +02:00 record converts to 00:15 UTC. The clock digits alone cannot answer.
Test time as a dependency
A clock dependency is a function that supplies time. Passing it in lets a rule be tested with fixed readings instead of sleeping or relying on the current machine clock.
Understand first
A retry rule should be testable exactly before, at and after expiry. Sleeping makes tests slow and unreliable. Separate obtaining time from deciding the result, then supply a monotonic clock for real elapsed deadlines.
Words you will see
- Dependency injection
- Passing a needed service into a rule rather than finding it secretly inside.
- Monotonic clock
- A clock intended for elapsed intervals whose readings do not go backward.
- Deadline
- A clock reading at which a time budget expires.
Evaluate the rule at three boundaries
remaining calls the supplied clock once. The iterator provides 8, then 10, then 12. Subtracting from deadline 10 gives 2, 0 and -2. max clamps the last value to 0 so callers never see a negative remaining budget.
The fake readings use one consistent arbitrary unit. They are not dates or Unix timestamps. A real deadline should be created and checked from the same clock source; combining a monotonic deadline with a wall-clock reading has no sensible subtraction meaning.
Keep current time out of deterministic business tests
A callable is any object that can be invoked with parentheses. Passing a small lambda is enough for this test; a framework is unnecessary. For calendar decisions, inject an aware current datetime instead and state the desired timezone.
The iterator has only three readings; a fourth call would raise StopIteration. That is a deliberate finite fixture, not a production clock implementation. No sleeps, processes, host timezone defaults or timing benchmarks are used.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return max(0, deadline - clock())Read time once and clamp an expired budget.
readings = iter([8, 10, 12])Prepare fixed before/at/after readings.
clock = lambda: next(readings)Supply one reading per call.
print(remaining(10, clock))The three identical call lines consume successive readings and print 2, 0, 0.
Inject a clock into business logic and test boundaries around midnight and DST. Avoid sleep-based tests for correctness. Do not mix aware and naive timestamps, silently discard offsets or infer a user's timezone from their language.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Move the deadline.
Try: Replace every remaining(10, clock) call with remaining(15, clock).
The outputs become 7, 5 and 3.
Observe the raw difference.
Try: Remove max(0, ...) and return deadline - clock().
The original last output becomes -2, changing the nonnegative-budget contract.
Before you move on
With a fixed clock returning 17 and a deadline of 15, what should remaining return?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
0. The raw difference is -2, but the rule deliberately reports an expired budget as zero rather than a negative allowance.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.