Sub topic 1
The Building Blocks: `date`, `time`, and `datetime`
Prerequisites
You should know basic Python imports, functions, and exceptions. This chapter assumes Python 3.9 or later and a basic idea of UTC and time zone offsets.
The building blocks: `date`, `time`, and `datetime`
Python's datetime module provides separate types for different parts of time:
daterepresents a calendar date, such as2026-11-26.timerepresents a clock time, such as11:07.datetimecombines a date and a clock time.timedeltarepresents a duration, such as three days or two hours.
from datetime import date, time, datetime, timedelta, timezone
day = date(2026, 11, 26)
clock = time(11, 7)
moment = datetime.combine(day, clock)
print(day)
print(clock)
print(moment)
print(moment + timedelta(days=10, hours=2))
naive = datetime(2026, 1, 1)
aware = datetime(2026, 1, 1, tzinfo=timezone.utc)
try:
print(naive < aware)
except TypeError as error:
print(error)datetime.combine() creates a datetime from a date and a time. You can add or subtract a timedelta to shift it.
Measuring and shifting time with `timedelta`
A timedelta stores a duration, not a calendar date. It supports units such as days, seconds, and microseconds.
tomorrow = day + timedelta(days=1)
two_hours_later = moment + timedelta(hours=2)
elapsed = two_hours_later - moment
print(tomorrow)
print(elapsed)Use a timedelta for elapsed time and simple shifts. Calendar rules such as daylight saving changes require extra care, covered later.
Naive and aware datetimes
A naive datetime has no time zone information. An aware datetime includes a tzinfo value that identifies its offset or time zone.
Python refuses to compare naive and aware datetimes because it cannot safely guess what the naive value means. Choose one convention and apply it consistently.
UTC and fixed offsets
UTC is the common reference time for storing and comparing instants. Python provides it as timezone.utc. A fixed offset is a constant difference from UTC, such as UTC+05:30. Fixed offsets do not model daylight saving or regional rules.
Exercise
Why does comparing a naive datetime with an aware datetime raise TypeError?
Show answer
The naive value has no time zone context, so Python cannot determine whether the two values represent comparable instants.