Timestamp2Date
← Back to blogs
•Unix TimestampPythonDateTime

Unix Timestamp Python Examples

Unix timestamp is the number of elapsed time units since 1970-01-01T00:00:00Z (Unix epoch).

In Python, one rule avoids most bugs:

  • use timezone-aware datetime
  • be explicit about seconds vs milliseconds

Python Unix Timestamp Cheatsheet

Get current timestamp

import time

now_sec = int(time.time())
now_ms = int(time.time() * 1000)
now_ns = time.time_ns()

Use int(...) for boundary checks like expiry logic.

Convert timestamp to datetime

from datetime import datetime, timezone

ts_sec = 1772668800

utc_dt = datetime.fromtimestamp(ts_sec, tz=timezone.utc)
local_dt = datetime.fromtimestamp(ts_sec)  # system local timezone

Convert datetime to timestamp

from datetime import datetime, timezone

dt = datetime(2026, 3, 5, 12, 0, 0, tzinfo=timezone.utc)
unix_sec = int(dt.timestamp())
unix_ms = int(dt.timestamp() * 1000)

Python 3.12 note (utcnow / utcfromtimestamp)

datetime.utcnow() and datetime.utcfromtimestamp() are deprecated in Python 3.12.

Prefer timezone-aware forms:

from datetime import datetime, timezone

now_utc = datetime.now(timezone.utc)
dt_utc = datetime.fromtimestamp(1772668800, tz=timezone.utc)

Parse ISO 8601 and get Unix seconds

from datetime import datetime

raw = "2026-03-05T12:00:00Z"
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
unix_sec = int(dt.timestamp())

Naive vs aware datetime (important)

from datetime import datetime, timezone

naive = datetime(2026, 3, 5, 12, 0, 0)
aware = datetime(2026, 3, 5, 12, 0, 0, tzinfo=timezone.utc)

print(int(naive.timestamp()))
print(int(aware.timestamp()))

A naive datetime is interpreted in local time. That can shift the Unix value unexpectedly.

Normalize unknown unit input (sec/ms)

def to_seconds(ts: int | float) -> float:
    value = float(ts)
    abs_value = abs(value)

    if 1e9 <= abs_value < 1e10:
        return value  # seconds

    if 1e12 <= abs_value < 1e13:
        return value / 1000.0  # milliseconds

    raise ValueError("Unsupported or ambiguous timestamp unit")

Compare expiry safely

import time


def is_expired(expires_at_sec: int) -> bool:
    return int(time.time()) >= expires_at_sec

Batch convert timestamps to UTC text

from datetime import datetime, timezone

values = [1772668800, 1772668860, 1772668920]
rows = [datetime.fromtimestamp(v, tz=timezone.utc).isoformat() for v in values]

Pandas quick tip

import pandas as pd

sec_series = pd.Series([1772668800, 1772668860])
dt_utc = pd.to_datetime(sec_series, unit="s", utc=True)

ms_series = pd.Series([1772668800000, 1772668860000])
dt_utc_ms = pd.to_datetime(ms_series, unit="ms", utc=True)

Digit-length quick guide

  • 10 digits: usually seconds
  • 13 digits: usually milliseconds
  • 16 digits: usually microseconds
  • 19 digits: usually nanoseconds

Common mistakes

  1. Using naive datetime and assuming UTC.
  2. Sending milliseconds to APIs that expect seconds.
  3. Mixing seconds and milliseconds in one database column.
  4. Comparing float seconds directly at exact boundaries.

Practical naming convention

Use unit-explicit names:

  • created_at_sec
  • updated_at_ms
  • expires_at_sec

Useful tools