gotchaMajorpending
Gotcha: Time zone handling in date comparisons
Viewed 0 times
timezoneutcnaive datetimeaware datetimetimestamptzdate parsing
Error Messages
Problem
Date comparisons fail or produce wrong results because of implicit timezone conversions or naive vs aware datetime handling.
Solution
Timezone pitfalls and safe patterns:
Rules:
# Python timezone dangers
from datetime import datetime, timezone
# BAD: Naive datetime (no timezone info)
now = datetime.now() # Local time, no tz info
utc_now = datetime.utcnow() # UTC time, but STILL no tz info!
# These can't be safely compared or stored!
now == utc_now # Comparing apples and oranges
# GOOD: Always use timezone-aware datetimes
now = datetime.now(timezone.utc) # UTC with tz info
# Or use: from zoneinfo import ZoneInfo (Python 3.9+)
from zoneinfo import ZoneInfo
la_time = datetime.now(ZoneInfo('America/Los_Angeles'))
# Converting between timezones
utc_time = la_time.astimezone(timezone.utc)// JavaScript timezone dangers
// Date.parse behavior varies by format!
new Date('2024-01-15'); // Parsed as UTC
new Date('2024-01-15T00:00:00'); // Parsed as LOCAL time!
new Date('2024-01-15T00:00:00Z'); // Parsed as UTC
// Adding 'Z' or offset makes it unambiguous
// Comparing dates across timezones
const d1 = new Date('2024-01-15T23:00:00-05:00'); // NYC
const d2 = new Date('2024-01-16T04:00:00Z'); // UTC
d1.getTime() === d2.getTime(); // true! Same instant-- PostgreSQL timezone pitfalls
-- TIMESTAMPTZ stores as UTC, displays in session timezone
SET timezone = 'America/New_York';
SELECT '2024-01-15 12:00:00+00'::timestamptz;
-- Displays: 2024-01-15 07:00:00-05 (converted to ET)
-- TIMESTAMP (without tz) stores literally, no conversion
-- ALWAYS use TIMESTAMPTZ for event times!Rules:
- Store dates in UTC
- Convert to local time only for display
- Always use timezone-aware types
- Be explicit about timezone in string parsing
Why
Timezone bugs are subtle because they only manifest for some users, in some regions, or during DST transitions. UTC internally with local display is the only safe pattern.
Context
Applications handling dates and times across timezones
Revisions (0)
No revisions yet.