The datetime module models dates, times, and timedeltas. Always store UTC in backends and convert for display—critical before timezone-aware Django models in the Django track.
date, datetime, timedelta
from datetime import date, datetime, timedelta, timezone
today = date.today()
now = datetime.now(timezone.utc)
later = now + timedelta(days=7)
Formatting and parsing
now.strftime("%Y-%m-%d")
datetime.strptime("2026-05-28", "%Y-%m-%d")
Prefer timezone-aware datetime objects for APIs—avoid naive local times in persisted data.
Important interview questions and answers
- Q: Naive vs aware datetime?
A: Aware datetimes include tzinfo; naive have no timezone—ambiguous for distributed systems. - Q: Why UTC in storage?
A: Single canonical timeline—convert to user locale at the edge.
Self-check
- What adds seven days to a datetime?
- Why avoid naive datetimes in APIs?
Pitfall: Naive datetimes cause timezone bugs—store UTC, convert for display; Django expands this in Django.
Interview prep
- Naive vs aware?
Aware includes tzinfo; naive lacks timezone—ambiguous for distributed systems.
- Why UTC storage?
Single timeline—convert to local zones at display layer.