Python time Module
How to work with Unix timestamps in Python using the time and datetime modules. Covers time.time(), conversions, formatting, and timezone handling.
Language
time.time()
Detailed Explanation
Python provides two primary modules for timestamp operations: time for low-level Unix timestamp work, and datetime for higher-level date manipulation. The function time.time() returns the current Unix timestamp as a floating-point number in seconds.
Getting the current timestamp:
import time
from datetime import datetime, timezone
# Seconds since epoch (float)
time.time() # 1700000000.123456
# Integer seconds
int(time.time()) # 1700000000
# Using datetime
datetime.now(timezone.utc).timestamp() # 1700000000.123456
Converting timestamps to dates:
# Timestamp to datetime (UTC)
dt = datetime.fromtimestamp(1700000000, tz=timezone.utc)
# datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc)
# WARNING: without tz, uses local timezone
datetime.fromtimestamp(1700000000) # local time — avoid this
# Timestamp to formatted string
dt.strftime("%Y-%m-%d %H:%M:%S") # "2023-11-14 22:13:20"
dt.isoformat() # "2023-11-14T22:13:20+00:00"
Converting dates to timestamps:
# String to timestamp
from datetime import datetime, timezone
dt = datetime(2024, 1, 15, 9, 30, 0, tzinfo=timezone.utc)
dt.timestamp() # 1705310600.0
# ISO format string to timestamp (Python 3.7+)
dt = datetime.fromisoformat("2024-01-15T09:30:00+00:00")
dt.timestamp()
Critical pitfall — naive vs. aware datetimes: A datetime object without timezone info is called "naive." Calling .timestamp() on a naive datetime assumes local time, which produces different results on different servers. Always use timezone-aware datetimes by passing tz=timezone.utc or using zoneinfo.ZoneInfo (Python 3.9+).
Performance measurement: For benchmarking, use time.perf_counter() or time.monotonic() instead of time.time(). These monotonic clocks are not affected by NTP adjustments or manual clock changes, making them reliable for measuring elapsed time.
Use Case
Python's time module is heavily used in backend services for cache TTL calculations, scheduling tasks, and recording timestamps in structured logs for observability pipelines.