Module 15 · Python Standard Libraries — topic 3 of 13
datetime
Dates and times with datetime: date, time, datetime and timedelta objects, arithmetic, formatting with strftime, parsing with strptime and fromisoformat, and time zones.
Learning objectives
- Create and compare dates and datetimes
- Do date arithmetic with timedelta
- Format, parse and convert between time zones
Definition
The datetime module provides date (year, month, day), time, datetime (both together) and timedelta (a duration). It supports arithmetic, comparison, formatting, parsing and time-zone-aware values.
Introduction
Due dates, ages, countdowns, schedules and logs all involve dates. Doing the arithmetic by hand is error-prone — months have different lengths and years can be leap years.
Why it matters
datetime handles calendars correctly and gives readable formatting, so your programs avoid off-by-one-day bugs.
Detailed explanation
date(2026, 11, 27) creates a date; date.today() and datetime.now() give the current values.
Subtracting dates gives a timedelta; adding a timedelta moves a date. timedelta supports days, seconds, minutes, hours and weeks.
strftime formats: %d day, %m month, %Y year, %H hour, %M minute, %A weekday name, %B month name. strptime parses text using the same codes.
date.fromisoformat and datetime.fromisoformat parse ISO 8601 strings like 2026-11-27 or 2026-11-27T18:45; isoformat() produces them.
A naive datetime has no time zone; an aware one has tzinfo. Fixed offsets use timezone(timedelta(hours=5, minutes=30)); named zones use zoneinfo.ZoneInfo("Asia/Kolkata") (on Windows the tzdata package may be needed).
astimezone converts an aware datetime to another zone. Store times in UTC and convert for display.
weekday() returns 0 for Monday through 6 for Sunday.
Syntax
- date, datetime, timedelta.
- strftime formats, strptime parses.
- Prefer aware datetimes in UTC.
Code examples
Date arithmetic
2026-11-27 4 Friday 27 November 2026 2026-12-27 35
Parsing and formatting
2026-11-27T18:45:00 06:45 PM Fri 25 Dec, 09:30
More examples
Time zones, ages and countdowns
2026-11-27 09:30:00+00:00 27 Nov 04:30 EST 25 34 days 5 hours
Step-by-step explanation
- The meeting time is aware (it has a time zone), so it converts correctly to UTC and to New York time.
- The age function subtracts one if the birthday hasn't happened yet this year; the tuple comparison handles month and day together.
- Subtracting datetimes gives a timedelta with days and remaining seconds.
Expected output
Running “Time zones, ages and countdowns” prints exactly:
Practical applications
- Library due dates and late fees.
- Scheduling meetings across time zones.
Best practices
- Store and compute in UTC; convert for display.
- Use ISO 8601 for data exchange.
- Use timedelta instead of manual day counting.
Common mistakes
Mixing naive and aware datetimes
Avoid
Prefer
Python refuses to compare or subtract naive and aware datetimes (TypeError).
Wrong format codes
Avoid
Prefer
Month 27 doesn't exist, so parsing fails with ValueError.
Important notes
- dateutil and other libraries add more parsing options, but the standard module covers most needs.
Key takeaways
- date, datetime and timedelta model dates and durations.
- strftime/strptime format and parse.
- Use aware datetimes for time zones.
Try it yourself
- 1Print the dates of the next four Mondays after a given date.
- 2Calculate a library fine of 5 rupees per day late from issue and return dates.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?