Python Datetime and Timezone Handling Prompt
Handle dates, times, timezones, and durations correctly in automation scripts — UTC-everywhere storage, aware datetimes, DST-safe scheduling, and reliable parsing/formatting of timestamps.
- Target user
- Automation engineers fighting off-by-an-hour bugs and naive-datetime crashes
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Python engineer who has audited the off-by-one-hour and "works until DST" bugs that plague time handling in automation.
I will provide:
- The script or function that touches dates/times
- Where timestamps come from (logs, APIs, user input, the system clock) and where they go (DB, files, other APIs)
- The Python version (so we know if `zoneinfo` is available — 3.9+)
Your job:
1. **Find the naive datetimes** — flag every `datetime.now()`, `datetime.utcnow()` (deprecated and dangerous), `fromtimestamp` without tz, and any arithmetic mixing aware and naive objects.
2. **Establish the discipline** — store and compute in UTC with timezone-aware objects (`datetime.now(timezone.utc)`), convert to local/display tz only at the edges. Make this rule explicit in a one-line comment at each boundary.
3. **Parse robustly** — use `datetime.fromisoformat` for ISO-8601, `zoneinfo.ZoneInfo("Region/City")` for named zones, and explain why parsing with `strptime` + `%Z` is unreliable. Handle the missing-timezone case explicitly rather than assuming local.
4. **Do DST-safe math** — show that adding `timedelta(days=1)` to wall-clock time is not the same as adding 24 hours across a DST boundary, and demonstrate the correct approach for "same time tomorrow" scheduling.
5. **Format for the audience** — UTC ISO-8601 with offset for logs and machines, human-readable local time for humans, and never log ambiguous local times without an offset.
6. **Cover monotonic needs** — recommend `time.monotonic()` for measuring elapsed time and timeouts, since wall-clock can jump backward via NTP.
7. **Test the edge cases** — leap seconds aside, write `pytest` cases for the DST fall-back ambiguous hour, the spring-forward gap, and a non-UTC input source.
Output as: (a) annotated before/after of the risky code, (b) a small `tz` helper module, (c) the pytest cases for DST boundaries.
Bias toward: aware-UTC everywhere, explicit conversion at boundaries, and never trusting the system local timezone implicitly.
Run this prompt with AI
Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.
Related prompts
-
Bash Cron-to-systemd-Timer Migration Prompt
Convert legacy crontab entries into equivalent systemd service+timer units with correct scheduling, logging, environment, and failure handling so scheduled jobs become observable and manageable.
-
Bash Word-Splitting and Quoting Hardening Prompt
Audit and rewrite a Bash script to eliminate unquoted-expansion bugs, unsafe word splitting, and glob injection while preserving intended behavior
-
Bash Exit-Code and Pipefail Propagation Audit Prompt
Audit a Bash script for swallowed failures, missing pipefail, and broken exit-code propagation through pipes, subshells, and command substitution
-
Bash getopts Long-Options Parser Prompt
Build a robust Bash option parser that supports both short flags and GNU-style long options with validation and a generated usage block
More Bash & Python Automation prompts & error guides
Browse every Bash & Python Automation prompt and troubleshooting guide in one place.
Reading prompts? Get all 500 in one free PDF
500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.
- 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
- Instant PDF download — yours free, forever
- Plus one practical AI-workflow email a week (no spam)
Single opt-in · unsubscribe anytime · no spam.