Python datetime in Depth
A timedelta is a length of time, like three days. Dates and datetimes can add and subtract these lengths.
Add and subtract time
timedelta works with days and weeks too.
from datetime import date, timedelta
start = date(2026, 10, 22)
print(start + timedelta(days=10))
print(start - timedelta(weeks=1))The gap between dates
Subtracting dates gives a timedelta. Its days attribute is a plain number.
from datetime import date, timedelta
print((date(2026, 11, 1) - date(2026, 10, 22)).days)
print(timedelta(days=2, hours=3))Naive meets aware
This mix is an error. Python refuses to guess the zone.
from datetime import datetime, timezone
naive = datetime(2026, 10, 22, 12, 0)
aware = datetime(2026, 10, 22, 12, 0, tzinfo=timezone.utc)
try:
print(naive < aware)
except TypeError as error:
print("TypeError:", error)UTC and fixed offsets
timezone.utc is the zero offset zone. You can also build a fixed offset.
from datetime import datetime, timedelta, timezone
utc_dt = datetime(2026, 10, 22, 9, 0, tzinfo=timezone.utc)
plus_two = datetime(2026, 10, 22, 9, 0, tzinfo=timezone(timedelta(hours=2)))
print(utc_dt)
print(plus_two.utcoffset())Parse ISO text
fromisoformat reads the standard ISO date format.
from datetime import date, datetime
print(datetime.fromisoformat("2026-10-22T14:30:00"))
print(date.fromisoformat("2026-10-22"))Example
from datetime import datetime, timedelta, timezone
start = datetime(2026, 10, 22, 9, 0, tzinfo=timezone.utc)
deadline = start + timedelta(days=7, hours=5)
print("Start:", start.isoformat())
print("Deadline:", deadline.isoformat())
print("Days left:", (deadline - start).days)Key points
- timedelta: a length of time, such as days or hours
- Use timedelta to add or subtract time from a date
- Subtracting two dates gives a timedelta
- Naive: a datetime with no time zone information
- Aware: a datetime that knows its time zone
In this example, the start is a fixed aware datetime in UTC. A timedelta of seven days and five hours is added to it. That gives the deadline. Subtracting the start from the deadline gives the gap. The days attribute shows seven whole days. No step uses the current time.
Note
You cannot compare a naive datetime with an aware one.
Python raises a TypeError.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What happens when you compare a naive datetime with an aware one?