Sub topic 10
Dates, times, datetimes, and timedeltas
This chapter assumes you know basic Python syntax, can call functions and read tracebacks, and can run a script or use the interactive interpreter. It also assumes you know how to import from the standard library, which an earlier chapter covered.
The datetime module has four core types. Knowing which one fits a value, and what each one cannot do, prevents most date bugs. Later chapters cover arithmetic in more depth, formatting and parsing, and time zones. Here the goal is the working model of the types themselves.
The four types
| Type | Holds | Example value |
|---|---|---|
| `date` | A calendar day: year, month, day | `2026-11-26` |
| `time` | A time of day: hour, minute, second, microsecond | `14:30:15.250000` |
| `datetime` | A date and a time together | `2026-11-26 14:30:00` |
| `timedelta` | A length of time, not a point in time | `2 days, 2:01:00` |
The first three describe a point on a calendar or clock. timedelta describes a distance between two points. Subtracting two points gives a distance, and adding a distance to a point gives a new point.
All four types are immutable. You never change an object in place. You build a new one.
Creating date, time, and datetime objects
Each type takes its parts as positional or keyword arguments, from the largest unit to the smallest.
from datetime import date, time, datetime
d = date(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)
t = time(14, 30, 15, 250000) # hour, minute, second, microsecond
print(t) # 14:30:15.250000
print(t.hour, t.minute, t.second, t.microsecond)
dt = datetime(2026, 11, 26, 14, 30)
print(dt) # 2026-11-26 14:30:00
print(dt.date()) # 2026-11-26
print(dt.time()) # 14:30:00
print(datetime.combine(d, t)) # 2026-11-26 14:30:15.250000Only the date parts are required for date and datetime. Omitted time parts default to zero, so datetime(2026, 11, 26) is midnight at the start of that day. A time defaults to 00:00:00.
weekday() and isoweekday() differ only in numbering. weekday() counts Monday as 0 and Sunday as 6. isoweekday() counts Monday as 1 and Sunday as 7. Mixing them up is a common off-by-one bug.
The current date and time
Three class methods read the system clock:
from datetime import date, datetime
print(date.today()) # today's date, for example 2026-11-26
print(datetime.now()) # the current local date and time
print(datetime.today()) # same as now() without a time zone argumentThe output depends on when you run it. datetime.now() returns a naive value in local time unless you pass a time zone. Naive values are discussed below.
Validation
The constructors check their arguments and raise ValueError for impossible values. They know the calendar, including leap years.
from datetime import date
for args in [(2026, 2, 30), (2026, 13, 1), (2024, 2, 29)]:
try:
print(date(*args))
except ValueError as exc:
print(args, "->", exc)The first two calls fail with messages such as day is out of range for month and month must be in 1..12. The third succeeds, because 2024 is a leap year.
Replacing parts and the supported range
Because objects are immutable, assigning to an attribute fails. Use replace() to get a modified copy.
from datetime import datetime
dt = datetime(2026, 11, 26, 14, 30, 45)
start_of_day = dt.replace(hour=0, minute=0, second=0)
print(start_of_day) # 2026-11-26 00:00:00
try:
dt.day = 1
except AttributeError:
print("datetime objects are immutable")The supported range is year 1 through year 9999. date.min is 0001-01-01 and date.max is 9999-12-31. Arithmetic that leaves this range raises OverflowError. Resolution for datetime and time is one microsecond.
timedelta: a length of time
A timedelta is built from any mix of weeks, days, hours, minutes, seconds, milliseconds, and microseconds. Every argument may be a float or negative. There is no months or years argument, because those units have no fixed length.
Internally a timedelta stores only three numbers, and it normalizes whatever you give it into them:
days, which may be negativeseconds, always from 0 to 86399microseconds, always from 0 to 999999
from datetime import timedelta
td = timedelta(days=1, hours=25, minutes=61)
print(td) # 2 days, 2:01:00
print(td.days) # 2
print(td.seconds) # 7260
print(td.total_seconds()) # 180060.0
print(timedelta(weeks=1)) # 7 days, 0:00:00
print(timedelta(milliseconds=1500)) # 0:00:01.500000The 25 hours and 61 minutes spilled over into extra days and hours. Notice that td.seconds is only the leftover seconds within the day, not the total length. This is a classic gotcha: td.seconds for a two-day span is not the number of seconds in two days. To get the whole length as one number, call total_seconds(), which returns a float.
Negative values normalize in a way that surprises people. Only days carries the sign:
from datetime import timedelta
neg = timedelta(hours=-1)
print(neg) # -1 day, 23:00:00
print(neg.days) # -1
print(neg.seconds) # 82800
print(neg.total_seconds()) # -3600.0The value means "minus one day, plus 23 hours", which equals minus one hour. If you read .days and .seconds separately on negative deltas, you will get wrong results. Use total_seconds() or abs() instead.
What you can do with these types
A timedelta supports addition, subtraction, scaling, and division:
from datetime import timedelta
a = timedelta(hours=3)
b = timedelta(minutes=30)
print(a + b) # 3:30:00
print(a - b) # 2:30:00
print(a * 2) # 6:00:00
print(a / b) # 6.0 (timedelta / timedelta gives a float)
print(a // b) # 6 (floor division gives an int)
print(a / 4) # 0:45:00Points and distances combine as described earlier:
from datetime import date, datetime, timedelta
d = date(2026, 11, 26)
print(d + timedelta(days=30)) # 2026-12-26
print(date(2027, 1, 1) - d) # 36 days, 0:00:00
print(datetime(2027, 1, 1) - datetime(2026, 11, 26, 14, 30)) # 35 days, 9:30:00Subtracting two date objects gives a timedelta whose .days is the answer. date + timedelta ignores everything smaller than a day, so it uses only the days part:
from datetime import date, timedelta
print(date(2026, 11, 26) + timedelta(hours=36)) # 2026-11-27
print(date(2026, 11, 26) + timedelta(hours=5)) # 2026-11-26That can look like silent data loss, so convert to datetime first when hours matter.
A time object does not support arithmetic at all. If you need "14:30 plus 45 minutes", combine the time with a date using datetime.combine, add the timedelta, and read .time() from the result.
Comparison rules and common errors
Objects of the same type compare naturally, with earlier values being smaller. Mixing types is where trouble starts.
from datetime import date, datetime
d = date(2026, 11, 26)
dt = datetime(2026, 11, 26)
print(d == dt) # False: different types are never equal
try:
print(d < dt)
except TypeError:
print("cannot order a date against a datetime")
print(dt.date() == d) # True: convert first, then comparedatetime is a subclass of date, so isinstance(dt, date) is True. That makes type checks easy to get wrong. When you test whether a value is a plain date, check for datetime first.
The errors you will meet most often with these types:
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: day is out of range for month` | An impossible calendar date | Validate input, or catch `ValueError` |
| `TypeError` when comparing | Comparing `date` with `datetime`, or naive with aware | Convert both sides to the same type |
| Wrong value from `td.seconds` | It holds only the leftover seconds within a day | Use `td.total_seconds()` |
| `AttributeError` on assignment | Objects are immutable | Use `replace()` |
| `OverflowError` | Result outside years 1 to 9999 | Check the range before adding large deltas |
| `TypeError` adding to a `time` | `time` has no arithmetic | Combine with a date first |
Naive and aware values, briefly
A datetime or time is naive when it carries no time zone information, and aware when it does. Everything above used naive values, which is fine for local scripts and for durations. Naive values cannot be safely compared with aware ones. The later chapter on time zones covers this in detail. For now, remember that a plain datetime(2026, 11, 26, 12, 0) has no zone and that datetime.now() returns local time without recording which zone that is.
Putting it together
This function reports how long until a deadline, using only the constructors and timedelta attributes from this chapter.
from datetime import datetime, timedelta
def describe_gap(now: datetime, deadline: datetime) -> str:
gap = deadline - now
if gap < timedelta(0):
return "overdue by " + str(-gap)
hours, remainder = divmod(int(gap.total_seconds()), 3600)
minutes = remainder // 60
return f"{hours} hours and {minutes} minutes left"
now = datetime(2026, 11, 26, 9, 0)
print(describe_gap(now, datetime(2026, 11, 27, 17, 45))) # 32 hours and 45 minutes left
print(describe_gap(now, datetime(2026, 11, 26, 8, 0))) # overdue by 1:00:00The function compares the gap to timedelta(0) to detect a negative span. It then works from total_seconds() rather than .seconds, which avoids the normalization trap.
Exercise
What do timedelta(hours=-1).days and timedelta(hours=-1).seconds return, and which attribute or method should you use to get -3600 as a single number?
Show answer
.days is -1 and .seconds is 82800, because a timedelta normalizes to a negative day plus a positive number of seconds (-1 day + 23 hours). Call total_seconds(), which returns -3600.0.
Exercise
Given d = date(2026, 11, 26), what does d + timedelta(hours=36) print, and why does it differ from datetime(2026, 11, 26) + timedelta(hours=36)?
Show answer
It prints 2026-11-27. Adding a timedelta to a date uses only the whole days (36 hours is 1 day plus 12 hours, so 1 day is added) and discards the rest. The datetime version keeps the hours and gives 2026-11-27 12:00:00.
Exercise
Write code that builds the datetime for noon on 29 February 2026 and explains what happens.
Show answer
datetime(2026, 2, 29, 12, 0) raises ValueError: day is out of range for month, because 2026 is not a leap year. Using 2028 instead, datetime(2028, 2, 29, 12, 0), works.