Convert a timestamp
Convert a Unix timestamp with datetime.fromtimestamp(ts, tz=timezone.utc). Without tz it uses the machine's zone, and milliseconds need a division by 1000.
A Unix timestamp has to become a date, and the result differs depending on where the script runs.
import os, time
from datetime import datetime, timezone
ts = 1767225600
print(datetime.fromtimestamp(ts, tz=timezone.utc))
print(datetime.fromtimestamp(ts, tz=timezone.utc).isoformat())
os.environ["TZ"] = "Asia/Tokyo"
time.tzset()
print(datetime.fromtimestamp(ts))
print(datetime.fromtimestamp(ts, tz=timezone.utc).astimezone())
try:
datetime.fromtimestamp(1767225600123)
except ValueError as e:
print("milliseconds:", e)
print(datetime.fromtimestamp(1767225600123 / 1000, tz=timezone.utc))2026-01-01 00:00:00+00:00
2026-01-01T00:00:00+00:00
2026-01-01 09:00:00
2026-01-01 09:00:00+09:00
milliseconds: year 57971 is out of range
2026-01-01 00:00:00.123000+00:00fromtimestamp takes seconds since the Unix epoch. With no tz argument it returns a naive datetime in the machine's local zone, which is why the same number prints two different times once TZ is changed. Passing tz=timezone.utc returns an aware value that means the same everywhere, as the datetime documentation explains. A value in milliseconds is read as a year far in the future and refused, so divide it by 1000 first.
The older utcfromtimestamp returns a naive value in UTC and is deprecated from Python 3.12, so avoid it in new code. Float seconds lose precision at the microsecond level for large values. zoneinfo.ZoneInfo("Asia/Tokyo") gives a named zone without touching the process-wide TZ.