The module's main classes are date, a calendar date with no time; time, a time of day with no date; datetime, a combination of both; and timedelta, a duration, the difference between two dates or datetimes. datetime objects can be naive, with no timezone information, or timezone-aware; naive datetimes are simpler to work with but can't be safely compared across different timezones, which is a common source of bugs in date-handling code. Formatting a datetime as text uses strftime, and parsing text into a datetime uses strptime, both driven by the same format-code mini-language.
1Understanding datetime Module
The module's main classes are date, a calendar date with no time; time, a time of day with no date; datetime, a combination of both; and timedelta, a duration, the difference between two dates or datetimes. datetime objects can be naive, with no timezone information, or timezone-aware; naive datetimes are simpler to work with but can't be safely compared across different timezones, which is a common source of bugs in date-handling code. Formatting a datetime as text uses strftime, and parsing text into a datetime uses strptime, both driven by the same format-code mini-language.
Prefer timezone-aware datetimes for anything that will be compared, stored, or displayed across different timezones — naive datetimes silently assume 'whatever timezone the reader has in mind', which causes subtle bugs when servers, users, and databases don't all agree.
from datetime import date
today = date(2026, 7, 23)
print(today)
print(today.strftime("%B %d, %Y"))2Practical Example
Here is a real-world application of datetime Module showing how it is used in production Python code.
from datetime import date, timedelta
today = date(2026, 7, 23)
next_week = today + timedelta(days=7)
print(next_week)3Best Practices
Follow these guidelines when working with datetime Module:
1. Use timedelta for date/time arithmetic, adding or subtracting durations, instead of manually calculating with seconds or days
2. Store and pass around timezone-aware datetimes in backend/server code, converting to a specific timezone only for display
3. Use strftime/strptime with explicit format strings for converting between datetime objects and text, rather than manual string manipulation
Tip: Prefer timezone-aware datetimes for anything that will be compared, stored, or displayed across different timezones — naive datetimes silently assume 'whatever timezone the reader has in mind', which causes subtle bugs when servers, users, and databases don't all agree.
from datetime import date
today = date(2026, 7, 23)
print(today)
print(today.strftime("%B %d, %Y"))