Date Calculator in Python with datetime, timedelta, and zoneinfo
I built a date calculator that performs timezone-aware arithmetic with datetime, timedelta, and the zoneinfo database, correctly handling daylight saving transitions. Using aware datetimes eliminated the off-by-an-hour bugs that plague naive timestamp math.
Objective & Context
Date math is deceptively error-prone: naive datetimes ignore timezones and DST. This lab computes durations and future dates with aware datetimes and zoneinfo, the correctness pattern behind scheduling and log-timestamp normalization.
Environment & Prerequisites
- Python 3.11 with datetime and zoneinfo (standard library).
- The system tz database available.
- Test cases spanning a DST boundary.
flowchart LR
N[now in zone] --> A[aware datetime]
A --> D[+ timedelta]
D --> C{DST boundary?}
C -->|handled by zoneinfo| R[correct result]
Step-by-Step Execution
1. Compute a future date in a timezone
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
now = datetime.now(ZoneInfo("America/Toronto"))
due = now + timedelta(days=30)
2. Difference between two dates
python -c "from datetime import date; print((date(2026,12,31)-date(2026,6,17)).days)"3. Format the output
python -c "from datetime import datetime; print(datetime.now().strftime('%Y-%m-%d %H:%M %Z'))"197
Validation & Testing
Add an interval that crosses the spring-forward DST change and confirm the wall-clock result is correct. Pass criteria: aware datetimes used throughout, DST handled by zoneinfo, and day-count differences match a manual calendar check.
Advanced: Troubleshooting
- Off-by-one-hour: never mix naive and aware datetimes; localize first.
- zoneinfo missing: install
tzdatawhere the OS lacks the tz database. - Wrong DST: use IANA names (America/Toronto), not fixed UTC offsets.
Key Results
- Eliminated off-by-an-hour bugs with timezone-aware datetimes.
- Handled DST transitions correctly via zoneinfo.
- Computed accurate day-count differences across months.
- Standardized IANA timezone names over fixed offsets.