AI Skill Report Card
Working with Datetime
Quick Start15 / 15
Pythonfrom datetime import datetime, date, time, timedelta, timezone # Current date/time now = datetime.now() today = date.today() # Create specific date/time dt = datetime(2024, 3, 15, 14, 30, 0) # Timezone-aware datetime (preferred over naive) utc_now = datetime.now(timezone.utc) # Parse a string into datetime dt = datetime.strptime("2024-03-15", "%Y-%m-%d") # Format a datetime into a string dt.strftime("%Y-%m-%d %H:%M:%S") # "2024-03-15 14:30:00" # ISO format (preferred for parsing/serialization) dt.isoformat() # "2024-03-15T14:30:00" datetime.fromisoformat("2024-03-15T14:30:00") # Arithmetic with timedelta tomorrow = today + timedelta(days=1) diff = dt2 - dt1 # returns timedelta
Recommendation▾
Add an example showing error handling for ambiguous/invalid date strings
Workflow14 / 15
Progress checklist for date/time handling tasks:
- Decide if you need
date,time,datetime, ortimedelta - Decide naive vs. timezone-aware (default to aware for anything crossing systems)
- Choose parsing method (
strptime,fromisoformat, or third-party if formats vary) - Perform arithmetic/comparisons using
timedelta - Format output with
strftimeorisoformat - Test edge cases: DST transitions, leap years, month/year boundaries
1. Choose the right type
date: calendar date only (year, month, day)time: time of day only (hour, minute, second, microsecond, tzinfo)datetime: combination of both — use this for almost everythingtimedelta: duration/difference between two dates or times
2. Naive vs. aware
Naive objects have no tzinfo — never compare naive and aware datetimes (raises TypeError). Always attach a timezone when the value will be stored, transmitted, or compared across systems:
Pythonfrom datetime import timezone, timedelta # UTC dt = datetime.now(timezone.utc) # Fixed offset tz = timezone(timedelta(hours=-5)) dt = datetime.now(tz) # Full IANA timezone support (Python 3.9+) from zoneinfo import ZoneInfo dt = datetime.now(ZoneInfo("America/New_York"))
3. Parsing input
- Known fixed format →
strptime(s, fmt) - ISO 8601 string →
datetime.fromisoformat(s)(handles most ISO variants natively in modern Python) - Unix timestamp →
datetime.fromtimestamp(ts, tz=timezone.utc)
4. Arithmetic and comparison
Pythondelta = timedelta(weeks=1, days=2, hours=3) future = now + delta diff = future - now # timedelta diff.total_seconds() # float seconds # Comparisons work directly if dt1 < dt2: ...
5. Formatting output
Pythondt.strftime("%A, %B %d, %Y") # "Friday, March 15, 2024" dt.isoformat(timespec="seconds")
Recommendation▾
Include a brief example contrasting a bad outcome (e.g., naive/aware comparison error) with the fix
Examples17 / 20
Example 1: Parse and reformat a date string
Input: "2024-03-15" needs to become "March 15, 2024"
Output:
Pythondt = datetime.strptime("2024-03-15", "%Y-%m-%d") dt.strftime("%B %d, %Y") # "March 15, 2024"
Example 2: Compute age in days between two dates
Input: date(1990, 5, 20) and date.today()
Output:
Pythondelta = date.today() - date(1990, 5, 20) delta.days # integer number of days
Example 3: Convert a UTC timestamp to a local timezone
Input: Unix timestamp 1710512400, target zone "Europe/Berlin"
Output:
Pythonfrom zoneinfo import ZoneInfo dt_utc = datetime.fromtimestamp(1710512400, tz=timezone.utc) dt_local = dt_utc.astimezone(ZoneInfo("Europe/Berlin"))
Example 4: Add 30 business-agnostic days to a deadline
Input: datetime(2024, 1, 1), add 30 days
Output:
Pythondeadline = datetime(2024, 1, 1) + timedelta(days=30) # datetime(2024, 1, 31)
Recommendation▾
Consider trimming slight overlap between Workflow section and Best Practices/Pitfalls to tighten length further
Best Practices
- Default to timezone-aware datetimes (
timezone.utcorzoneinfo.ZoneInfo) for anything persisted or shared. - Use
datetime.fromisoformat/.isoformat()for serialization instead of custom string formats — it round-trips cleanly. - Store datetimes in UTC; convert to local timezone only for display.
- Use
timedeltafor durations rather than manually computing seconds/days. - Prefer
zoneinfo(stdlib, Python 3.9+) overpytzfor timezone handling in new code. - Use
total_seconds()when you need a numeric duration from atimedelta, not.seconds(which discards days).
Common Pitfalls
- Comparing or subtracting a naive and an aware datetime — raises
TypeError. - Using
datetime.utcnow()— deprecated; it returns a naive datetime despite the name. Usedatetime.now(timezone.utc)instead. - Assuming
timedelta.secondsgives total duration — it only gives the seconds component; usetotal_seconds(). - Manually applying fixed UTC offsets for timezones that observe DST — use
zoneinfoinstead of hardcoded offsets. - Forgetting that
%z/%Zinstrptimerequire the input string to actually contain offset/timezone info. - Mutating date/time objects — they are immutable; arithmetic always returns new objects.