datetime.fromtimestamp / utcfromtimestamp
Epoch seconds in, datetime out. With tz=UTC the answer is the same on every machine; without tz it is the machine's local time, and date.fromtimestamp is always local.
Demo
from datetime import datetime, timedelta, timezone datetime.fromtimestamp(0, timezone(timedelta(hours=0))).isoformat()
1790683200 is 2026-09-29 12:00 UTC, shown here at +02:00 as 14:00. 86400000 is one day in milliseconds, but read as seconds it is 1000 days: 1972-09-27. Millisecond timestamps of today overflow completely — Linux raises ValueError for the year beyond 9999 (as this demo does), Windows OSError: [Errno 22] Invalid argument.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| timestamp | int | float | yes | Seconds since 1970-01-01T00:00:00Z. Fractions become microseconds, rounded half to even. |
| tz | tzinfo | None | no (None) | None: naive local time (depends on the machine). A tzinfo: aware result in that zone. date.fromtimestamp has no tz. |
Return value
datetime — Aware in tz when tz is given; otherwise naive local time. date.fromtimestamp returns the local date.
Common patterns
from datetime import datetime, UTC dt = datetime.fromtimestamp(ts, UTC)
from datetime import datetime, UTC dt = datetime.fromtimestamp(ms / 1000, UTC)
import os from datetime import datetime, UTC modified = datetime.fromtimestamp(os.stat(path).st_mtime, UTC)
Examples
Pitfalls
import warnings from datetime import datetime with warnings.catch_warnings(): warnings.simplefilter("ignore") dt = datetime.utcfromtimestamp(1790683200) dt.tzinfo is None
from datetime import datetime, UTC datetime.fromtimestamp(1790683200, UTC)
from datetime import datetime, UTC datetime.fromtimestamp(86400000, UTC)
from datetime import datetime, UTC datetime.fromtimestamp(86400000 / 1000, UTC)
When to use
- Epoch values from databases, logs, os.stat, APIs
- Always with tz (usually UTC) unless you really want machine-local time
- utcfromtimestamp → fromtimestamp(ts, UTC)
- ISO 8601 text → fromisoformat
Notes
FAQ
datetime.fromtimestamp(ts, UTC) for an aware UTC datetime (use timezone.utc before Python 3.11). Without the tz argument you get naive local time of the machine running the code.