Python Dates 📅
The datetime Module
A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
📆 Analogy: The Digital Calendar
Think of the datetime module as a super-powered Digital Calendar & Stopwatch.
- It knows exactly what time it is right now (now()).
- It can calculate "3 days from now" without you counting on your fingers (timedelta).
- It can write the date in any language or format you want (strftime).
✨ Current Date and Time
python
import datetime
now = datetime.datetime.now()
print(now)
# Output: 2023-10-27 14:30:00.123456🛠️ Creating Date Objects
To create a date, use the datetime() constructor.
python
# Year, Month, Day
x = datetime.datetime(2020, 5, 17)
print(x)📝 Formatting Dates (strftime)
The strftime() method formats date objects into readable strings.
python
x = datetime.datetime(2018, 6, 1)
print(x.strftime("%B")) # June (Full month name)
print(x.strftime("%A")) # Friday (Full weekday name)
print(x.strftime("%Y-%m-%d")) # 2018-06-01⏳ Time Deltas
You can calculate the difference between two dates or add time to a date using timedelta.
python
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
print(f"Tomorrow: {tomorrow}")✨ Pro Tip: ISO Format
When storing dates in a database or API, always use the standard ISO 8601 format. Python makes this easy:
python
import datetime
x = datetime.datetime.now()
print(x.isoformat()) # 2023-10-27T14:30:00.123456💡 Common Format Codes
%a: Weekday short (Wed)%A: Weekday full (Wednesday)%b: Month short (Dec)%B: Month full (December)%d: Day (01-31)%m: Month (01-12)%Y: Year (2023)%H: Hour (00-23)%M: Minute (00-59)%S: Second (00-59)