Understand the core Python classes for dates, times, and durations.
How It Works
datetime provides date for calendar dates, time for wall-clock times, datetime for date and time together, and timedelta for durations. Use timezone-aware datetimes for cross-system timestamps; naive values have no timezone interpretation attached.
Step-by-Step Example
from datetime import date, datetime, time, timedelta, timezone
print(date(2026, 10, 17))
print(time(9, 30).isoformat())
print((datetime(2026, 10, 17, tzinfo=timezone.utc) + timedelta(days=1)).date())
Understanding the Example
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
2026-10-17
09:30:00
2026-10-18
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Use ZoneInfo for geographic time zones that change their UTC offset.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Combining naive local datetimes with aware UTC datetimes without converting them explicitly.
- Create a calendar date, a clock time, and a three-day duration.
Key Takeaways
- Understand the core Python classes for dates, times, and durations.
- datetime provides date for calendar dates, time for wall-clock times, datetime for date and time together, and timedelta for durations.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.