Unix Timestamp in Python

Use the standard library `datetime` module. For timezone-heavy work, the `pendulum` package is more ergonomic.

Common Operations

Get current Unix timestamp (seconds)

import time
ts = int(time.time())
# 1706745600

Get current Unix timestamp (milliseconds)

import time
ts_ms = int(time.time() * 1000)
# 1706745600000

Convert Unix timestamp to datetime (UTC)

from datetime import datetime, timezone
dt = datetime.fromtimestamp(1706745600, tz=timezone.utc)
# datetime(2024, 1, 31, 22, 40, tzinfo=timezone.utc)

Convert datetime to Unix timestamp

from datetime import datetime, timezone
dt = datetime(2024, 1, 31, 22, 40, tzinfo=timezone.utc)
ts = int(dt.timestamp())
# 1706740800

Parse ISO 8601 string

from datetime import datetime
dt = datetime.fromisoformat('2024-01-31T12:00:00+00:00')
# Python 3.11+ also handles the 'Z' suffix

Format as ISO 8601

dt.isoformat()
# '2024-01-31T12:00:00+00:00'

Other Languages

Need the full converter? Open the Timestamp Converter →