Focused practice · 9 min read

Python datetime Exercises: Dates, Deltas, and Formatting

Dates look simple until month lengths, leap years, and time zones appear. The datetime module handles the calendar rules for you. The main skill is choosing the right object: a date, a duration, or a specific instant.

Create and inspect a date

date validates the year, month, and day. isoformat produces a stable YYYY-MM-DD string that sorts correctly. Use the year, month, and day attributes when you need the parts separately.

from datetime import date
start = date(2026, 1, 15)
print(start.isoformat())
print(start.year, start.month, start.day)

A validated calendar date

Add a duration

timedelta stores a length of time, not a date. Adding it returns a new date and respects month and year boundaries. Subtraction returns a timedelta, whose days attribute gives the difference.

from datetime import date, timedelta
start = date(2026, 1, 30)
end = start + timedelta(days=3)
print(end.isoformat())
print((end - start).days)

Date arithmetic

Format with a stable pattern

strftime turns a date into text. Numeric patterns such as %Y/%m/%d are predictable across locales. Month and weekday names can change with the machine's language settings, so avoid them in stored data.

from datetime import date
day = date(2026, 10, 27)
print(day.strftime("%Y/%m/%d"))
print(day.isoformat())

Numeric formatting

Distinguish dates from instants

A date answers which day it is. A datetime with a timezone answers which moment it is. Add tzinfo when you mean an instant that people in different regions observe. Do not attach a timezone just to make a date look complete.

from datetime import datetime, timezone
moment = datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc)
print(moment.isoformat())

A timezone-aware moment

Parse only when the format is known

strptime turns text into a datetime using an explicit pattern. Keep the same pattern in one place so writing and reading cannot drift apart. For user-supplied dates, validate errors instead of assuming the text is well formed.

from datetime import datetime
day = datetime.strptime("2026-10-27", "%Y-%m-%d")
print(day.date().isoformat())

Text back to a date

Your practice checklist

Common questions

Does timedelta handle leap years?

Yes. Adding days to a date follows the calendar, including leap years.

What is the difference between date and datetime?

date has only year, month, and day. datetime also has a time and can carry timezone information.

Why does strftime show a different month name on another computer?

Month and weekday names depend on locale. Numeric patterns avoid that variation.

Practice dates

12 questions on date creation, timedeltas, differences, formatting, and timezone-aware values.

Open practice

Keep reading: