Python: Convert Timestamp to Date
Python's datetime module provides multiple ways to convert a Unix timestamp to a date. The right method depends on whether you want UTC or local time, and whether you need a timezone-aware or naive datetime object. Python 3 strongly encourages using timezone-aware datetimes to avoid subtle bugs in time zone handling.
The most important distinction in Python timestamp conversion is between fromtimestamp() (which returns local time as a naive datetime) and utcfromtimestamp() (which returns UTC as a naive datetime). For production code, the recommended approach is to use fromtimestamp(ts, tz=timezone.utc), which returns a timezone-aware datetime in UTC that can be converted to any other timezone.
All Python timestamp-to-date patterns
UTC (naive datetime — simple but avoid in production):
from datetime import datetime
datetime.utcfromtimestamp(1700000000)
→ datetime(2023, 11, 14, 22, 13, 20)
UTC (timezone-aware — recommended):
from datetime import datetime, timezone
datetime.fromtimestamp(1700000000, tz=timezone.utc)
→ datetime(2023, 11, 14, 22, 13, 20, tzinfo=datetime.timezone.utc)
Local time:
datetime.fromtimestamp(1700000000) # uses system timezone
Format as string:
datetime.utcfromtimestamp(1700000000).strftime('%Y-%m-%d %H:%M:%S')
→ '2023-11-14 22:13:20'
With arrow library (third-party, very readable):
import arrow
arrow.get(1700000000).format('YYYY-MM-DD HH:mm:ss')