Lesson 20 of 30
Working with Dates and Times
The datetime module: parsing, formatting, arithmetic, and timezones.
The datetime Module
from datetime import datetime, date, timedelta
now = datetime.now()
print(now)
print(now.year, now.month, now.day)
print(now.strftime("%d/%m/%Y %H:%M"))
today = date.today()
print(today)
Formatting Dates
| Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2026 |
| %m | Month (01–12) | 03 |
| %d | Day (01–31) | 05 |
| %H | Hour 24h | 14 |
| %M | Minute | 30 |
| %A | Full weekday | Thursday |
Parsing Dates
dt = datetime.strptime("25/12/2026", "%d/%m/%Y")
print(dt) # 2026-12-25 00:00:00
Date Arithmetic with timedelta
today = date.today()
deadline = today + timedelta(days=30)
print(f"Deadline: {deadline}")
diff = date(2026, 12, 31) - today
print(f"Days until New Year: {diff.days}")