A timestamp quantifies an instant as a scalar value, usually the count of seconds elapsed since the Unix epoch (1970-01-01 00:00:00 UTC). Python represents these values with the standard numeric types int (for whole seconds) and float (when sub‑second precision is needed).
Obtaining integer and floating‑point timestamps
The time.time() fucntion returns a floating‑point number, which can be cast to an integer to discard the fractional part. Alternatives like time.time_ns() provide nanosecond precision and can be used to build a whole‑second integer.
import time
raw_ts = time.time()
int_ts = int(raw_ts)
nano_ts = time.time_ns()
int_from_nano = nano_ts // 1_000_000_000
print(f"Float timestamp: {raw_ts}")
print(f"Integer timestamp (via int()): {int_ts}")
print(f"Integer timestamp (via nanoseconds): {int_from_nano}")
Converting between timestamps and datetime objects
The datetime module bridges epoch‑based timestamps and calendar‑aware representations. Starting from a datetime object, timestamp() produces a float. The inverse uses fromtimestamp().
from datetime import datetime, timezone
# Start with a concrete datetime
original = datetime(2025, 4, 8, 14, 30, 0, tzinfo=timezone.utc)
ts = original.timestamp()
# Reconstruct from timestamp
restored = datetime.fromtimestamp(ts, tz=timezone.utc)
print(f"Original datetime : {original}")
print(f"Timestamp : {ts}")
print(f"Restored datetime : {restored}")
To work without timezone awareness, omit the tz parameter for naive local time handling.
Formatting timestamps for human‑readable output
Formatting converts a timestamp into a styled string. time.strftime accepts a format string and a struct_time tuple, which can be20obtained from the timestamp via localtime() or gmtime().
import time
stamp = time.time()
struct_local = time.localtime(stamp)
custom_format = time.strftime("%A, %B %d %Y %I:%M:%S %p", struct_local)
print(f"Formatted local time: {custom_format}")
By changing the format string,14you control the exact appearance (ISO 8601, locale‑specific, etc.).
Visualising the conversion workflow
The following sequence diagram, expressed in Mermaid, illustrates a typical timestamp‑to‑datetime‑and‑back interaction:
sequenceDiagram
participant Caller
participant TimeLib
Caller->>TimeLib: time.time()
TimeLib-->>Caller: float timestamp
Caller->>TimeLib: datetime.fromtimestamp(ts)
TimeLib-->>Caller: datetime object
Caller->>TimeLib: dt_obj.timestamp()
TimeLib-->>Caller: float timestamp
A consistnet mental model of these conversions makes it straightforward to mix integer seconds, floating‑point details, and human‑oriented date‑time strings within any Python project.