Convert Unix Timestamp in Python

Python provides robust timestamp handling through the datetime andtime modules. Python uses seconds (with optional decimals for microseconds) for Unix timestamps.

Unix Timestamp to Datetime

Python
from datetime import datetime, timezone

# From Unix timestamp (seconds)
timestamp = 1704067200
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
print(dt)  # 2024-01-01 00:00:00+00:00
print(dt.isoformat())  # 2024-01-01T00:00:00+00:00

# From milliseconds (divide by 1000)
timestamp_ms = 1704067200000
dt = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc)
print(dt)  # 2024-01-01 00:00:00+00:00

Datetime to Unix Timestamp

Python
from datetime import datetime, timezone
import time

# Current timestamp
now_timestamp = time.time()
print(now_timestamp)  # e.g., 1704067200.123456

# Current timestamp (integer seconds)
now_seconds = int(time.time())
print(now_seconds)  # e.g., 1704067200

# From datetime object
dt = datetime(2024, 1, 1, 0, 0, 0, tzinfo=timezone.utc)
timestamp = dt.timestamp()
print(timestamp)  # 1704067200.0
print(int(timestamp))  # 1704067200

Timezone Handling

Python 3.9+
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

timestamp = 1704067200

# UTC
dt_utc = datetime.fromtimestamp(timestamp, tz=timezone.utc)
print(dt_utc)  # 2024-01-01 00:00:00+00:00

# Specific timezone (Python 3.9+)
dt_ny = datetime.fromtimestamp(timestamp, tz=ZoneInfo("America/New_York"))
print(dt_ny)  # 2023-12-31 19:00:00-05:00

dt_tokyo = datetime.fromtimestamp(timestamp, tz=ZoneInfo("Asia/Tokyo"))
print(dt_tokyo)  # 2024-01-01 09:00:00+09:00

# Convert between timezones
dt_utc = datetime.fromtimestamp(timestamp, tz=timezone.utc)
dt_la = dt_utc.astimezone(ZoneInfo("America/Los_Angeles"))
print(dt_la)  # 2023-12-31 16:00:00-08:00

String Formatting

Python
from datetime import datetime, timezone

timestamp = 1704067200
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)

# Various formats
print(dt.strftime("%Y-%m-%d"))           # 2024-01-01
print(dt.strftime("%B %d, %Y"))          # January 01, 2024
print(dt.strftime("%Y-%m-%d %H:%M:%S"))  # 2024-01-01 00:00:00
print(dt.strftime("%A, %B %d, %Y"))      # Monday, January 01, 2024

# ISO format
print(dt.isoformat())  # 2024-01-01T00:00:00+00:00

Common Pitfalls

Naive vs Aware Datetimes

Always use timezone-aware datetime objects. Naive datetimes assume local time, leading to bugs.

# ❌ Wrong - naive datetime (no timezone)
dt = datetime.fromtimestamp(1704067200)
# Uses local timezone, inconsistent across servers

# ✅ Correct - timezone-aware
dt = datetime.fromtimestamp(1704067200, tz=timezone.utc)

Milliseconds vs Seconds

Python expects seconds. If you have milliseconds from JavaScript or Java, divide by 1000.

# ❌ Wrong - passing milliseconds as seconds
datetime.fromtimestamp(1704067200000)  # OverflowError!

# ✅ Correct - convert milliseconds to seconds
datetime.fromtimestamp(1704067200000 / 1000, tz=timezone.utc)

DST Ambiguity

During DST transitions, local times can be ambiguous. Use fold parameter (Python 3.6+) to disambiguate, or work in UTC.

Edge Cases

Python
from datetime import datetime, timezone

# Negative timestamps (before 1970)
dt = datetime.fromtimestamp(-86400, tz=timezone.utc)
print(dt)  # 1969-12-31 00:00:00+00:00

# Sub-second precision
timestamp = 1704067200.123456
dt = datetime.fromtimestamp(timestamp, tz=timezone.utc)
print(dt)  # 2024-01-01 00:00:00.123456+00:00
print(dt.microsecond)  # 123456

# Maximum timestamp (platform-dependent)
# Typically up to year 3000+ on 64-bit systems

Frequently Asked Questions

What module should I use for Unix timestamps in Python?

Use the datetime module for most timestamp operations. The time module provides lower-level functions, while third-party libraries like Arrow or Pendulum offer more features.

Does Python use seconds or milliseconds for Unix timestamps?

Python uses seconds (with optional decimal for sub-second precision). This differs from JavaScript which uses milliseconds.

How do I handle timezones in Python?

Use timezone-aware datetime objects with datetime.timezone.utc or the zoneinfo module (Python 3.9+). Avoid naive datetime objects for timestamp conversions.

What is the difference between time.time() and datetime.timestamp()?

time.time() returns the current Unix timestamp directly. datetime.timestamp() converts a datetime object to a Unix timestamp. Both return seconds as a float.