Between Epoch and datetime

Medium ⏱ 12 min 59% acceptance ★★★★★ 4.8
Write to_epoch(dt_obj) converting a naive UTC datetime to an integer Unix timestamp with .replace(tzinfo=timezone.utc).timestamp(), and from_epoch(ts) converting back via datetime.fromtimestamp(ts, tz=timezone.utc). Round-tripping must preserve the value.

Examples

Example 1
Input
from_epoch(to_epoch(datetime(2026, 1, 1, tzinfo=None)))
Output
datetime(2026, 1, 1, tzinfo=timezone.utc)
Explanation

Attach UTC on the way out, read it back explicitly.

Constraints

  • Treat naive inputs as UTC.
  • to_epoch returns int.

Topics

Date & Timeunix timestamps

Companies

UberStripeCloudflare

Hints

Hint 1

Naive datetimes have no zone — attach one before .timestamp().

Hint 2

fromtimestamp with tz=timezone.utc avoids local-zone surprises.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.