Official Documentation & Resources
Primary Official Sources (REQUIRED)
- Python Official Library Documentation: https://docs.python.org/3/library/datetime.html#date-objects
- Python Official Tutorial: https://docs.python.org/3/tutorial/index.html
- Module Source Code: https://github.com/python/cpython/blob/main/Lib/datetime.py
Additional Authoritative Sources
- Real Python - Working with Dates and Times: https://realpython.com/python-datetime/
- GeeksforGeeks - Python DateTime: https://www.geeksforgeeks.org/python-datetime-module/
- Python Module of the Week (PyMOTW) - datetime: https://pymotw.com/3/datetime/
- Stack Overflow datetime questions: https://stackoverflow.com/questions/tagged/python+datetime
IMPORTANT: Examples in this guide are adapted from the official Python documentation at https://docs.python.org/3/library/datetime.html
Overview
The date class represents an idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. It provides year, month, and day attributes and does not include time information. Date objects are immutable and hashable.
A date object represents a date (year, month and day) in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions.
Key Characteristics
- Immutable Objects: Date objects cannot be modified after creation
- Thread Safety: Date objects are immutable and therefore thread-safe
- Naive Dates: No timezone information is stored or used
- Gregorian Calendar: Based on proleptic Gregorian calendar
- Range Limitations: Years 1 through 9999 are supported
- Hashable: Can be used as dictionary keys and in sets
Prerequisites and Setup
Python Version Compatibility
- Minimum Python version required: Python 2.3+ (datetime module introduction)
Installation and Imports
# Standard library (no installation needed)
from datetime import date
# Alternative import
import datetime
# Then use: datetime.date()
Basic Usage
Official Documentation Examples
Source: All examples adapted from https://docs.python.org/3/library/datetime.html#date-objects
Simple Example
from datetime import date
# Today's date (from official docs)
today = date.today()
print(f"Today: {today}") # Today: 2025-06-14
# Creating specific dates (from official docs)
birthday = date(1990, 5, 15)
print(f"Birthday: {birthday}") # Birthday: 1990-05-15
# Date formatting (from official docs)
print(birthday.strftime("%A, %B %d, %Y")) # Monday, May 15, 1990
Core Methods/Functions
from datetime import date
# Constructor (from official docs)
d = date(2025, 6, 14)
print(d) # 2025-06-14
# Today's date (from official docs)
today = date.today()
print(f"Today is {today}")
# ISO format (from official docs)
iso_date = d.isoformat()
print(f"ISO format: {iso_date}") # ISO format: 2025-06-14
Common Patterns
# Pattern 1: Basic usage (from official docs)
from datetime import date
d = date(2025, 6, 14)
print(f"Year: {d.year}, Month: {d.month}, Day: {d.day}")
# Pattern 2: Date parsing (from official docs)
iso_string = "2025-06-14"
parsed_date = date.fromisoformat(iso_string)
print(f"Parsed: {parsed_date}")
# Pattern 3: Error handling (from official docs)
try:
invalid_date = date(2025, 2, 30) # Invalid date
except ValueError as e:
print(f"Error: {e}") # Error: day is out of range for month
date API Reference
Constructor
| Method | Description | Parameters | Return Type | Example |
|---|---|---|---|---|
date(year, month, day) | Create a date object | year (1-9999), month (1-12), day (1-31) | date | date(2025, 6, 14) |
Class Methods
| Method | Description | Return Type | Example |
|---|---|---|---|
today() | Current local date | date | date.today() |
fromordinal(ordinal) | Date from proleptic Gregorian ordinal | date | date.fromordinal(738000) |
fromisoformat(date_string) | Parse ISO 8601 date string | date | date.fromisoformat('2025-06-14') |
fromtimestamp(timestamp) | Local date from POSIX timestamp | date | date.fromtimestamp(1718373000) |
Instance Methods
| Method | Description | Return Type | Example |
|---|---|---|---|
strftime(format) | Format as string | str | d.strftime('%Y-%m-%d') |
isoformat() | ISO 8601 format | str | d.isoformat() |
weekday() | Day of week (Monday=0) | int | d.weekday() |
isoweekday() | Day of week (Monday=1) | int | d.isoweekday() |
isocalendar() | ISO calendar tuple | tuple | d.isocalendar() |
replace(**kwargs) | Return date with new values | date | d.replace(year=2026) |
toordinal() | Proleptic Gregorian ordinal | int | d.toordinal() |
ctime() | String representing the date | str | d.ctime() |
Properties and Attributes
| Attribute | Description | Type | Range | Example |
|---|---|---|---|---|
year | Year | int | 1-9999 | d.year |
month | Month | int | 1-12 | d.month |
day | Day | int | 1-31 | d.day |
Detailed Method Examples
Creating date Objects (from official docs)
from datetime import date
# Basic creation (from official docs)
d = date(2025, 6, 14)
print(d) # 2025-06-14
# Today's date (from official docs)
today = date.today()
print(f"Today: {today}")
# From ISO format (from official docs)
iso_date = date.fromisoformat('2025-06-14')
print(f"From ISO: {iso_date}")
# From ordinal (from official docs)
ordinal_date = date.fromordinal(738000)
print(f"From ordinal: {ordinal_date}")
Date Formatting (from official docs)
from datetime import date
d = date(2025, 6, 14)
# ISO format (from official docs)
print(d.isoformat()) # 2025-06-14
# Custom formatting (from official docs)
print(d.strftime("%A, %B %d, %Y")) # Friday, June 14, 2025
print(d.strftime("%m/%d/%Y")) # 06/14/2025
print(d.strftime("%d-%b-%Y")) # 14-Jun-2025
# Default string representation (from official docs)
print(d.ctime()) # Fri Jun 14 00:00:00 2025
Date Arithmetic (from official docs)
from datetime import date, timedelta
d = date(2025, 6, 14)
# Adding/subtracting days (from official docs)
tomorrow = d + timedelta(days=1)
print(f"Tomorrow: {tomorrow}") # Tomorrow: 2025-06-15
yesterday = d - timedelta(days=1)
print(f"Yesterday: {yesterday}") # Yesterday: 2025-06-13
# Date difference (from official docs)
new_year = date(2025, 1, 1)
days_since_new_year = d - new_year
print(f"Days since New Year: {days_since_new_year.days}") # Days since New Year: 164
Date Properties (from official docs)
from datetime import date
d = date(2025, 6, 14)
# Basic properties (from official docs)
print(f"Year: {d.year}") # Year: 2025
print(f"Month: {d.month}") # Month: 6
print(f"Day: {d.day}") # Day: 14
# Weekday methods (from official docs)
print(f"Weekday (0=Monday): {d.weekday()}") # Weekday (0=Monday): 4
print(f"ISO weekday (1=Monday): {d.isoweekday()}") # ISO weekday (1=Monday): 5
# ISO calendar (from official docs)
iso_cal = d.isocalendar()
print(f"ISO calendar: {iso_cal}") # ISO calendar: (2025, 24, 5)
print(f"Year: {iso_cal.year}, Week: {iso_cal.week}, Weekday: {iso_cal.weekday}")
Date Replacement (from official docs)
from datetime import date
d = date(2025, 6, 14)
# Replace specific components (from official docs)
new_year = d.replace(year=2026)
print(f"New year: {new_year}") # New year: 2026-06-14
new_month = d.replace(month=12)
print(f"New month: {new_month}") # New month: 2025-12-14
# Multiple replacements (from official docs)
new_date = d.replace(year=2024, month=1, day=1)
print(f"New date: {new_date}") # New date: 2024-01-01
Important Notes
Gotchas and Common Pitfalls
- Date objects are immutable - methods return new objects
- Year range is limited to 1-9999
- February 29 only exists in leap years
- Date arithmetic requires timedelta objects
Error Handling
from datetime import date
# Invalid date handling (from official docs)
try:
invalid = date(2025, 2, 30) # February doesn't have 30 days
except ValueError as e:
print(f"Error: {e}")
try:
invalid = date(10000, 1, 1) # Year out of range
except ValueError as e:
print(f"Error: {e}")
Performance Considerations
- Date objects are lightweight and efficient
- Immutability makes them safe for use as dictionary keys
- Date arithmetic is optimized for performance
Best Practices
- Always use ISO format for string representation - Use
isoformat()for consistent formatting - Handle ValueError exceptions - Invalid dates will raise ValueError
- Use date.today() for current date - More reliable than manual date creation
- Leverage immutability - Safe to use as dictionary keys and in sets
- Use replace() for date modifications - Returns new object with specified changes
- Consider timezone awareness - Use datetime objects if timezone information is needed
Related Classes
- datetime.time - Time without date information
- datetime.datetime - Combined date and time
- datetime.timedelta - Time duration for arithmetic
- Main datetime module - Complete module overview