Skip to content
shellhacks.dev
Python

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.

1 min read
Summarize in AI

A Unix timestamp has to become a date, and the result differs depending on where the script runs.

Python
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))
Text
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:00

fromtimestamp 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.

Share

More snippets

Python

Read a CSV file

Read a CSV file with csv.reader and open it with newline=''. Without that argument a line break inside a quoted field is changed before the parser sees it.

2 min read
Python

Generate a UUID

Generate a random UUID with uuid.uuid4() and a repeatable one with uuid.uuid5(namespace, name). The hex attribute gives the form without hyphens.

2 min read
Python

Base64 encode a string

Encode with base64.b64encode(), which takes and returns bytes, so encode the string first and decode the result. The URL-safe variant swaps two characters.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.