Lesson · Date, Time & Numbers
Date & Time
61 min readDate & Time
Dates and times become difficult when calendars, formatting, and time zones interact. Use aware datetimes at system boundaries and treat naive values only as deliberately local or abstract times.
Learning goals
- Create an aware datetime in a named zone with
ZoneInfoand explain what the attached zone adds. - Add and subtract
timedeltaintervals and predict whether the result stays aware. - Convert an instant between zones with
astimezoneand show that the instant itself is unchanged. - Format a datetime with
isoformatand parse ISO 8601 text back withfromisoformat. - Explain the difference between naive and aware values and why mixing them raises
TypeError.
Mental model
Awareness is the property that turns a wall-clock reading into an instant: only aware values can be compared or subtracted across machines. From an aware value, timedelta arithmetic moves along the timeline, while astimezone only changes which zone describes the same point.
Mental model
read it top to bottom
naive datetime a wall-clock label with no zone (ambiguous instant) ↓ attach a ZoneInfo aware datetime an exact point on the timeline ↓ + timedelta ↓ astimezone(other zone) a later instant the same instant, relabeled
Core idea
A datetime is either a label (naive) or an instant (aware, with a zone attached). timedelta arithmetic moves along the timeline, astimezone relabels the same instant for another region, and mixing aware with naive values fails loudly because the interpreter cannot guess which zone was meant. Keep naive values for abstract times and make everything crossing a boundary aware.
datetime
datetime combines a calendar date with a time of day in one object. Its now(tz) classmethod attaches a zone when one is passed, subtraction between two aware values yields a timedelta, and isoformat() renders the value as ISO 8601 text.
date
date represents a calendar date (year, month, day) with no time of day and no zone. Subtracting two dates yields a timedelta measured in days.
time
time represents a clock time independent of any particular day, optionally carrying a tzinfo. It fits values such as opening hours, where the calendar date does not participate.
timedelta
timedelta represents a fixed duration stored as days, seconds, and microseconds. Adding or subtracting one from a date or datetime returns a new object; neither operand is mutated.
Formatting
Formatting renders a datetime as text: isoformat() produces the ISO 8601 form, and strftime() follows explicit format codes such as %Y-%m-%d %H:%M. Use the ISO form for exchange between programs and strftime for human-facing layouts.
Parsing
Parsing turns text into a datetime: datetime.fromisoformat() handles ISO 8601 strings, while datetime.strptime() accepts the same format codes as strftime for other layouts. A string that does not match the expected pattern raises ValueError.
Time zones
Time zones represent civil-time rules that can change by date. Use zoneinfo and aware datetimes when an instant must survive daylight-saving transitions and regional rule changes.
Aware vs naive datetimes
An aware datetime carries enough time-zone information to locate an instant relative to UTC. A naive datetime lacks that context and is easy to misinterpret at system boundaries.
zoneinfo
zoneinfo provides IANA time-zone data integration in the standard library. Prefer named zones for civil-time rules instead of fixed offsets when daylight-saving changes matter.
Walkthrough
datetime.now(ZoneInfo("Asia/Kolkata"))reads the system clock and attaches the named zone, sonowis aware with a+05:30offset; the zone object carries the full rule history, not just today's offset.now + timedelta(hours=3)produces a datetime three hours later, still labeledAsia/Kolkata:timedeltais a fixed duration, and adding one never changes the zone.later.astimezone(ZoneInfo("UTC"))keeps the instant and changes the label: the UTC clock reading is five and a half hours behind the Kolkata reading of the same moment.- Predict before running: the offset in the first printed line, and whether the second line shows the same wall-clock time as the first or a shifted one.
Experiments to try
- Print
now.tzinfoand then build the naivedatetime(2026, 10, 4, 12, 0); subtract it from an aware value and read theTypeError. - Add
timedelta(days=1)todate(2024, 2, 28), then add one more day, and print both results; name the calendar rule behind the two outputs. - Parse
"2026-10-04T12:00:00+05:30"withfromisoformat, convert it withastimezone(ZoneInfo("UTC")), and check with==that both objects name the same instant. - Print the
utcoffset()ofZoneInfo("Europe/London")for a January date and a July date, then compare both with a fixedtimezone(timedelta(hours=0))offset.
Common mistakes
- Subtracting or comparing a naive datetime with an aware one: Python raises
TypeErrorbecause the naive value offers no zone to align with, so attach a zone deliberately before mixing the two. - Calling
datetime.now()at a system boundary: the naive result depends on the machine's local zone, so two servers can label the same event with different strings; capture the time with an explicit zone instead. - Replacing a named zone with a fixed offset:
timezone(timedelta(hours=5, minutes=30))matches Kolkata all year, but for a zone with daylight saving a fixed offset is wrong for half the year;ZoneInfocarries the rules. - Reading
astimezoneas moving the clock: it converts the label for the same instant, so a value and its converted copy compare equal even though their printed clock times differ.
Practice: Easy
- Run the worked example and print
nowitself; compare its offset with the UTC line and state how far apart the two clock readings are. - Print
type(now.tzinfo), build the naivedatetime(2026, 10, 4, 12, 0), and call.tzinfoon both; say which value is aware and which is not. - Add
timedelta(days=1)todate(2024, 2, 28), print the result, add one more day, print again, and name the calendar rule behind the two outputs.
Practice: Medium
- Write
same_instant(first, second)that reports whether two aware datetimes with different zones name the same moment; test it with a value and its ownastimezoneconversion, then with two values ten minutes apart. - Write
hours_between(start_text, end_text)that parses two ISO 8601 strings withfromisoformat, subtracts them, and returns the duration in hours; test it with offsets that differ, such as+05:30againstUTC. - Find the current UTC offset of
ZoneInfo("Europe/London")for a January date and a July date usingutcoffset(); explain which mechanism changes the number.
Practice: Hard
- Design a meeting converter
to_zone(iso_text, zone_name)that parses ISO text, converts it withastimezone, and returns ISO text; define what the function does when the input string carries no offset. - Failure lab: trigger the naive-versus-aware
TypeError, aValueErrorfromstrptimewith a mismatched layout, and aZoneInfoNotFoundErrorfrom an unknown zone key; explain what each error says about the input. - Connect this lesson to the standard data formats module: JSON has no datetime type, so values cross as ISO 8601 strings; describe the round trip (serialize with
isoformat, parse withfromisoformat) and one way the offset can be lost.
Lesson checklist
- I can build an aware datetime and point to where its zone information lives.
- I can add a
timedeltaand say whether the result is naive or aware. - I can convert an instant between zones and show that the instant did not change.
- I can parse and format ISO 8601 text, and say when
strptimeis needed instead.
Remember
Dates and times split into two kinds of value: aware datetimes that name an instant, and naive ones that name only a label. `ZoneInfo` supplies the zone rules, `timedelta` moves along the timeline, `astimezone` relabels the same instant, and `isoformat` with `fromisoformat` moves values across the text boundary without losing the offset.
Interview angles
What is the main purpose of **datetime**?+
datetime combines a calendar date with a time of day in one object; constructing it with a tzinfo such as ZoneInfo("UTC") makes it aware. Subtracting two aware datetimes yields a timedelta, and isoformat() renders the value as ISO 8601 text.
What should you pay attention to when using **date**?+
date holds a calendar date (year, month, day) with no time of day and no zone. Subtracting two dates produces a timedelta counted in days, which is the tool for calendar arithmetic such as deadlines.
How does **time** fit into this lesson?+
time holds a clock time independent of any particular day, optionally carrying a tzinfo. It fits values like opening hours, where the date does not participate.
Why does subtracting a naive datetime from an aware one raise `TypeError` instead of returning a timedelta?+
The naive value carries no zone, so the interpreter cannot align it to the aware value's timeline and refuses instead of guessing. Attach a zone to the naive value first, or keep both values naive on purpose.