Sub topic 1
The building blocks: date, time, and datetime
Almost every time-related bug in Python comes from using these three types without knowing what each one holds. This chapter covers date, time, and datetime from the standard datetime module. You will learn how to build them, read their parts, change them, compare them, and avoid the errors that catch most people. Durations, time zones, and parsing each get their own chapter later. This chapter only introduces them where it has to.
Prerequisites
This chapter assumes you have the following:
- Basic Python syntax: functions, imports,
try/except, and f-strings. - Python 3.9 or later. Later chapters use
zoneinfo, which was added in 3.9. - A rough idea of what UTC and a time zone offset are. You do not need to use them yet.
Three types, three jobs
The module separates a calendar day from a time of day, and gives you a third type that holds both.
| Type | Holds | Example value | Time zone support |
|---|---|---|---|
| `date` | year, month, day | `2026-11-26` | None |
| `time` | hour, minute, second, microsecond | `11:07:00` | Optional `tzinfo` |
| `datetime` | everything above | `2026-11-26 11:07:00` | Optional `tzinfo` |
Use the smallest type that matches your data. A birthday is a date. "The shop opens at 09:00" is a time. "The deploy finished at this moment" is a datetime. Storing a birthday as a datetime invents a time of day that nobody meant, and that invented value later causes comparison bugs.
Working with date
Build a date from a year, month, and day, in that order. All three arguments are required.
from datetime import date
d = date(2026, 11, 26)
print(d) # 2026-11-26
print(d.year, d.month, d.day) # 2026 11 26
print(d.weekday()) # 3 (Monday is 0)
print(d.isoweekday()) # 4 (Monday is 1)
print(d.isocalendar().week) # 48
print(d.replace(day=1)) # 2026-11-01The two weekday methods differ only in numbering. weekday() counts Monday as 0 and Sunday as 6. isoweekday() counts Monday as 1 and Sunday as 7. Pick one and stick to it, because mixing them gives off-by-one errors that only appear on certain days.
Other ways to get a date:
date.today()returns today's date from the system clock, in the machine's local zone.date.fromisoformat("2026-11-26")parses theYYYY-MM-DDform.date.fromordinal(n)counts days from 0001-01-01, which is day 1.
Invalid values raise ValueError
The constructor checks that the date exists in the calendar.
from datetime import date
try:
date(2026, 2, 29)
except ValueError as e:
print("invalid:", e) # invalid: day is out of range for month2026 is not a leap year, so the call fails. The same check hits replace(). Calling date(2026, 3, 31).replace(month=2) fails because February has no 31st. Python never "rolls over" to the next month for you. If you need the last day of a month, ask the calendar module instead of doing the arithmetic yourself:
import calendar
from datetime import date
def last_day_of_month(year: int, month: int) -> date:
return date(year, month, calendar.monthrange(year, month)[1])
print(last_day_of_month(2026, 2)) # 2026-02-28
print(last_day_of_month(2028, 2)) # 2028-02-29calendar.monthrange() returns a pair: the weekday of the first day of the month and the number of days in it.
Subtracting dates
Subtracting two dates gives a timedelta, which is a duration. The .days attribute is the number of whole days.
from datetime import date
today = date(2026, 11, 26)
year_end = date(2026, 12, 31)
print((year_end - today).days) # 35
print(today < year_end) # TrueWorking with time
A time object is a time of day with no date attached. Only the hour is required. The rest default to 0.
from datetime import time
t = time(11, 7)
print(t) # 11:07:00
print(t.hour, t.minute, t.second) # 11 7 0
print(time(23, 59, 59, 999999)) # 23:59:59.999999
print(time.min, time.max) # 00:00:00 23:59:59.999999
print(t.isoformat(timespec="minutes")) # 11:07
print(time(9) < time(17)) # TrueTwo things to keep in mind:
- There is no arithmetic.
time(11, 7) + timedelta(hours=1)raisesTypeError. A bare time of day does not know whether adding 14 hours crosses midnight. If you need to shift it, combine it with a date first and usedatetime. - Midnight is a valid value.
time(0, 0)counts as true in a boolean test (bool(time(0, 0))isTrue) since Python 3.5. Older code that treated midnight as falsy no longer applies.
Use time for recurring schedules, such as opening hours, where the date is not part of the data.
Working with datetime
A datetime takes the date arguments first, then the time arguments. Hour, minute, second, and microsecond are optional and default to 0.
from datetime import datetime
dt = datetime(2026, 11, 26, 11, 7, 59, 123456)
print(dt) # 2026-11-26 11:07:59.123456
print(dt.date()) # 2026-11-26
print(dt.time()) # 11:07:59.123456
print(dt.replace(microsecond=0)) # 2026-11-26 11:07:59
print(dt.isoformat()) # 2026-11-26T11:07:59.123456
print(dt.isoformat(sep=" ", timespec="seconds"))# 2026-11-26 11:07:59print() shows a space between the date and the time. isoformat() uses a T by default, as the ISO 8601 standard writes it. The sep argument switches between the two forms.
Combining a date and a time
datetime.combine() joins an existing date and time. It is the cleanest way to build a value when you collect the two parts separately, such as from two form fields. Adding a timedelta then shifts the result.
from datetime import date, time, datetime, timedelta
d = date(2026, 11, 26)
t = time(11, 7)
dt = datetime.combine(d, t)
print(dt) # 2026-11-26 11:07:00
print(dt + timedelta(days=10, hours=2)) # 2026-12-06 13:07:00The shifted result lands on 6 December at 13:07. The timedelta carried the month boundary for you.
Getting the current moment
datetime.now() returns the current local date and time. It is a convenient call, and also a common source of bugs, because the result is naive. A naive datetime has no time zone attached, so nothing in the object says which zone it is in. Chapter 3 covers this in detail. For now, treat datetime.now() as "a clock reading with no label".
Do not use datetime.utcnow() or datetime.utcfromtimestamp(). They were deprecated in Python 3.12 because they return naive values that look like local time but are not. The replacement is datetime.now(timezone.utc), which is covered later.
Fields, ranges, and immutability
Each field has a fixed range, and out-of-range values raise ValueError.
| Field | Valid range |
|---|---|
| `year` | 1 to 9999 (`datetime.MINYEAR` and `datetime.MAXYEAR`) |
| `month` | 1 to 12 |
| `day` | 1 to the number of days in that month |
| `hour` | 0 to 23 |
| `minute` | 0 to 59 |
| `second` | 0 to 59 |
| `microsecond` | 0 to 999999 |
| `fold` | 0 or 1 (used for daylight saving, covered later) |
There are no leap seconds in this model. A value like second=60 is rejected, so a timestamp from a system that reports 23:59:60 must be handled before it reaches datetime.
All three types are immutable: once created, they cannot change. Methods like replace() return a new object and leave the original untouched. Immutable values are hashable, so you can use them as dictionary keys and set members.
from datetime import date
d = date(2026, 11, 26)
first_of_month = d.replace(day=1)
print(d, first_of_month) # 2026-11-26 2026-11-01
events = {d: "release", first_of_month: "planning"}
print(events[date(2026, 11, 26)]) # releaseA frequent mistake is calling d.replace(day=1) and discarding the result, as if it modified d in place. It does not.
Where the types meet: datetime is a subclass of date
datetime inherits from date. That means isinstance(datetime(2026, 11, 26), date) is True, and code that checks isinstance(x, date) also accepts datetimes. It also creates a trap when you compare the two.
from datetime import date, datetime
d = date(2026, 11, 26)
dt = datetime(2026, 11, 26)
print(dt == d) # False
try:
print(dt < d)
except TypeError as e:
print("TypeError:", e)
print(dt.date() == d) # TrueEquality returns False without an error, even though both values describe the same day. Ordering (<) raises TypeError. The fix is to convert explicitly with dt.date(), so you decide what "the same" means.
Another asymmetry is arithmetic. Adding a timedelta to a date uses only the days part of the duration. Hours, minutes, and seconds are dropped:
from datetime import date, timedelta
print(date(2026, 11, 26) + timedelta(hours=30)) # 2026-11-27
print(date(2026, 11, 26) + timedelta(hours=23)) # 2026-11-26Thirty hours is one day and six hours, so the date moves forward one day. Twenty-three hours contains no whole day, so the date does not move at all. If you want hour-level accuracy, use a datetime.
Strings: str, repr, and isoformat
str() and isoformat() give readable text. repr() gives an unambiguous form that you can paste back into code, which is what you see in logs and the REPL.
from datetime import date
d = date(2026, 11, 26)
print(str(d)) # 2026-11-26
print(repr(d)) # datetime.date(2026, 11, 26)Prefer isoformat() when writing a value to a file, a log line, or an API. Its output sorts correctly as plain text and does not depend on the reader's locale. A later chapter covers strptime and strftime for other layouts.
Common errors
- Guessing argument order.
date(26, 11, 2026)raisesValueErrorbecause 26 is not a valid month. The order is always year, month, day. - Leading zeros.
date(2026, 08, 1)is aSyntaxErrorin Python 3. Write8, not08. - Ignoring the return value of
replace(). The original is unchanged. - Mixing
dateanddatetimein comparisons. See the warning above. - Treating
datetime.now()as a universal timestamp. It is local and naive. Two machines in different zones produce values that cannot be compared safely. - Using
timefor durations.time(90, 0)fails because the hour must be below 24. A length of time is atimedelta.
Exercise
What happens when you run date(2026, 3, 31).replace(month=2), and why?
Show answer
It raises ValueError ("day is out of range for month"). replace() builds a new date with day 31 and month 2, and February 2026 has only 28 days. Python does not roll over or clamp the day, so you must choose a valid day yourself, for example with calendar.monthrange().
Exercise
A page shows events whose start is a datetime. The code if event.start == date.today(): never matches, and no error appears. Explain the bug and write a fix.
Show answer
A datetime never equals a date, so == returns False without raising. Convert one side so both are dates: if event.start.date() == date.today():. Both sides are then plain dates and compare by calendar day.
Exercise
You have d = date(2026, 11, 26) and t = time(11, 7). Write one expression that gives the datetime 90 minutes after the two combined, and state its value.
Show answer
datetime.combine(d, t) + timedelta(minutes=90) gives 2026-11-26 12:37:00. The time type cannot do arithmetic, so you combine first and add the timedelta to the datetime.