Python theorytheory 0/50 · 0%
Tooling · medium

28. Working with dates and times

The datetime module for timestamps and durations.

`datetime` provides `date`, `time`, `datetime`, and `timedelta` for representing points in time and durations.

python
from datetime import datetime, timedelta, timezone

now = datetime.now(timezone.utc)
later = now + timedelta(hours=1)
now.isoformat()
datetime.fromtimestamp(1700000000, tz=timezone.utc)

Blockchain timestamps are typically Unix epoch seconds (`int`); convert with `datetime.fromtimestamp(ts, tz=timezone.utc)`, and always prefer timezone-aware datetimes to avoid ambiguity across environments.

Check your understanding

  1. 1. What does `timedelta(hours=1)` represent?

  2. 2. What does `datetime.fromtimestamp(ts, tz=timezone.utc)` do?

  3. 3. Why prefer timezone-aware datetimes?