Working with `datetime`
Standard Library
Mastering datetime
Handle timestamps like a pro: parsing ISO strings, building time zone–aware objects, and doing arithmetic safely.
Cheatsheet
| Task | Code |
|---|---|
| Current UTC time | datetime.datetime.utcnow() |
| Current local time | datetime.datetime.now() |
| Parse ISO string | datetime.datetime.fromisoformat('2024-03-13T09:00:00') |
| Format string | ts.strftime('%Y-%m-%d %H:%M') |
| Add 7 days | ts + datetime.timedelta(days=7) |
Time zones
- Use the
zoneinfomodule (Python 3.9+) for IANA timezone data.
from datetime import datetime
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo('UTC'))
local = now.astimezone(ZoneInfo('America/New_York'))
- Always store timestamps in UTC internally; convert at boundaries.
Best practices
- Use
datetime.datefor date-only values anddatetime.timefor time-only. - Serialize to ISO 8601 strings for APIs (
dt.isoformat()). - Beware naive vs aware datetimes—mixing them raises
TypeError.