Unix timestamps in Python
Everything Python needs for Unix timestamps: the current epoch time in seconds and milliseconds, timestamp-to-date and date-to-timestamp conversion, and ISO 8601 parsing. Always pass tz=timezone.utc. A naive datetime silently uses the machine's local zone, which is the root of most Python timestamp bugs. There's a live converter at the bottom for checking any value the snippets produce.
Get the current Unix timestamp
import time
seconds = int(time.time()) # 1700000000
millis = time.time_ns() // 1_000_000 # 1700000000000Convert a timestamp to a datetime
from datetime import datetime, timezone
dt = datetime.fromtimestamp(1700000000, tz=timezone.utc)
# datetime(2023, 11, 14, 22, 13, 20, tzinfo=timezone.utc)Without tz=, fromtimestamp() returns the machine's local wall time as a naive datetime: fine on your laptop, wrong on a UTC server.
Convert a datetime to a timestamp
seconds = int(dt.timestamp())On a naive datetime, .timestamp() assumes local time. Attach a timezone first.
Parse an ISO 8601 string
dt = datetime.fromisoformat("2023-11-14T22:13:20+00:00")
dt = datetime.fromisoformat("2023-11-14T22:13:20Z") # Python 3.11+Before 3.11, fromisoformat() rejects the trailing Z; replace it with +00:00.
Check a value
Detected: Unix timestamp (seconds)
Your timezone
UTC · GMT+00:00 · UTC
Tue, Nov 14, 2023, 10:13:20 PM
Common formats
UTC
Tue, Nov 14, 2023, 10:13:20 PM
ISO 8601
2023-11-14T22:13:20.000Z
Unix (seconds)
1700000000
Unix (millis)
1700000000000
Relative
…
World clock
Los Angeles PST
Tue, Nov 14, 2023, 02:13:20 PM
GMT-08:00
Chicago CST
Tue, Nov 14, 2023, 04:13:20 PM
GMT-06:00
New York EST
Tue, Nov 14, 2023, 05:13:20 PM
GMT-05:00
London GMT
Tue, Nov 14, 2023, 10:13:20 PM
GMT+00:00
Paris CET
Tue, Nov 14, 2023, 11:13:20 PM
GMT+01:00
Kolkata IST
Wed, Nov 15, 2023, 03:43:20 AM
GMT+05:30
Shanghai CST
Wed, Nov 15, 2023, 06:13:20 AM
GMT+08:00
Tokyo JST
Wed, Nov 15, 2023, 07:13:20 AM
GMT+09:00
Sydney AEDT
Wed, Nov 15, 2023, 09:13:20 AM
GMT+11:00
Common questions
- Why is my converted time off by several hours?
- A naive datetime leaked in somewhere. datetime.now(), fromtimestamp() without tz=, and fromisoformat() on a zone-less string all produce naive values that Python treats as local time. Pass timezone.utc explicitly at every boundary.
- How do I get milliseconds in Python?
- time.time_ns() // 1_000_000 avoids the float precision issues of int(time.time() * 1000). For a datetime, use int(dt.timestamp() * 1000).
- What replaced datetime.utcnow()?
- datetime.now(timezone.utc). utcnow() is deprecated since 3.12 because it returns a naive datetime that lies about being UTC.