Python ยท Chapter 32 of 45
Dates & Times
The `datetime` module provides `date`, `time`, `datetime`, and `timedelta` classes.
Use `datetime.now()` for the current time and `strftime()` / `strptime()` to convert between strings and dates.
Arithmetic with timedelta
Subtract two datetimes to get a `timedelta`. Add/subtract a `timedelta` to shift a datetime.
Formatting
`strftime('%Y-%m-%d')` formats a datetime. `strptime(str, '%Y-%m-%d')` parses a string.
Example 1 (python)
from datetime import datetime, timedelta
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))
print(now + timedelta(days=7))Output
2026-07-29 12:34
2026-08-05 12:34:56.789012Get now, format it, and add a week.
Example 2 (python)
from datetime import datetime
d = datetime.strptime("2024-01-15", "%Y-%m-%d")
print(d.year, d.month, d.day)Output
2024 1 15Parse a date string.
Key points
- Use the `datetime` module for date/time work.
- `timedelta` represents durations.
- `strftime` = format, `strptime` = parse.
- For timezone-aware code, use `zoneinfo` (Python 3.9+).
๐ก Note: Always store timestamps in UTC in a database, and convert to the user's timezone only when displaying.
