Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you work with dates, times and time zones correctly?

IntermediateConceptOS, filesystem, subprocess & CLIs
Answer

Always use timezone-aware UTC datetimes in automation.

from datetime import UTC, datetime, timedelta
now = datetime.now(UTC)
cutoff = now - timedelta(days=90)
datetime.fromisoformat("2026-01-05T10:00:00+00:00")
now.isoformat(timespec="seconds")

boto3 returns aware datetimes (StartTime, LaunchTime). Comparing them with a naive datetime.now() raises TypeError: can't compare offset-naive and offset-aware datetimes. datetime.utcnow() is deprecated since 3.12 because it returns a naive value. For local display use zoneinfo.ZoneInfo("Asia/Kolkata").

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs