Modules & Packages
datetime Module
Working with dates, times, and time deltas
Interview: Common in interviews — timezone handling and date arithmetic are practical skills
The datetime module provides classes for working with dates, times, and time intervals. It's one of the most used standard library modules, essential for logging, scheduling, data processing, and any time-sensitive application.
Core Classes
- date: Year, month, day —
date(2026, 6, 12) - time: Hour, minute, second, microsecond —
time(14, 30, 0) - datetime: Combines date and time —
datetime(2026, 6, 12, 14, 30) - timedelta: Duration between two dates/times —
timedelta(days=7, hours=3) - timezone: Fixed UTC offset —
timezone.utcortimezone(timedelta(hours=5))
Formatting and Parsing
- strftime: Format datetime to string —
dt.strftime("%Y-%m-%d %H:%M") - strptime: Parse string to datetime —
datetime.strptime("2026-06-12", "%Y-%m-%d") - ISO format:
dt.isoformat()— standard "2026-06-12T14:30:00" format - fromisoformat:
datetime.fromisoformat("2026-06-12T14:30:00")— parse ISO strings (Python 3.7+)
Naive vs Aware Datetimes
A naive datetime has no timezone info; an aware datetime has timezone. NEVER compare naive and aware datetimes — it raises TypeError. For production code, always use timezone-aware datetimes (UTC internally, convert for display).
Use zoneinfo for Timezones
Python 3.9+ includes zoneinfo for IANA timezone support: from zoneinfo import ZoneInfo; tz = ZoneInfo("America/New_York"). No more external pytz dependency.
Use Cases
Logging with timestamps for debugging and auditing
Scheduling tasks and calculating deadlines with timedelta
Working with APIs that use ISO 8601 date formats
Timezone conversion for global applications
Age, duration, and business day calculations
Common Mistakes
Using naive datetimes in production — always use timezone-aware (UTC internally)
Comparing naive and aware datetimes — raises TypeError; make both aware or both naive
Using datetime.now() instead of datetime.now(timezone.utc) — ambiguous local time
Not knowing timedelta.total_seconds() — .seconds only gives seconds within the day
Formatting with wrong codes — %m is month (number), %M is minute; %Y is year, %y is 2-digit year