Sub topic 5
Getting the current time and working with timestamps
This chapter assumes you know the datetime and timedelta types, and the difference between naive and aware datetimes. You should also know what UTC is. Here you will get the current time safely and convert between datetimes and POSIX timestamps.
Getting the current time
The main function is datetime.now(). What it returns depends on its argument.
| Call | Result |
|---|---|
| `datetime.now()` | Naive datetime in the machine's local time |
| `datetime.now(timezone.utc)` | Aware datetime in UTC |
| `datetime.now(ZoneInfo("Asia/Tokyo"))` | Aware datetime in that zone |
| `datetime.utcnow()` | Naive datetime holding UTC values (deprecated since Python 3.12) |
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
local_naive = datetime.now()
utc_now = datetime.now(timezone.utc)
tokyo_now = datetime.now(ZoneInfo("Asia/Tokyo"))
print(local_naive.tzinfo)
print(utc_now.tzinfo)
print(tokyo_now.tzinfo)The first line prints None, because the datetime is naive. The other two print UTC and Asia/Tokyo.
What a POSIX timestamp is
A POSIX timestamp counts the seconds since the Unix epoch, which is 1970-01-01 00:00:00 UTC. It has no time zone, so one number names one instant everywhere. Leap seconds are ignored. That makes timestamps compact and easy to compare, store, and send between systems.
Converting in both directions
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
ts = now.timestamp()
back = datetime.fromtimestamp(ts, tz=timezone.utc)
print(back == now)This prints True. timestamp() returns a float, and fromtimestamp() rebuilds the datetime. The tz argument is required for an aware result. Without it, you get a naive datetime in the machine's local time.
You can also convert a known timestamp straight into any zone:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
ts = 1_700_000_000
print(datetime.fromtimestamp(ts, tz=timezone.utc))
print(datetime.fromtimestamp(ts, tz=ZoneInfo("Asia/Tokyo")))
print(datetime.fromtimestamp(0, tz=timezone.utc))The output is:
2023-11-14 22:13:20+00:00
2023-11-15 07:13:20+09:00
1970-01-01 00:00:00+00:00Both of the first two lines describe the same instant. Only the display differs.
Naive datetimes and `timestamp()`
Calling .timestamp() on a naive datetime does not fail. Python assumes the value is local time and uses the machine's zone to compute the result. The same code therefore returns different numbers on a laptop set to New York and a server set to UTC. This is a quiet source of bugs. Make the datetime aware before you call .timestamp().
Common timestamp pitfalls
- Units. Python uses seconds. JavaScript and many APIs use milliseconds. Divide by 1000 before calling
fromtimestamp(). A millisecond value passed as seconds usually raises an error or gives a year far in the future. - Floats. A float holds about microsecond precision for present-day values, which matches
datetime. If you need exact round trips over long periods, store integer seconds, or integer microseconds, instead of floats. - Platform limits. Very large or negative timestamps can raise
OverflowError,OSError, orValueError, depending on the operating system.
Measuring elapsed time
The wall clock can jump. The system administrator can change it, or a network time service can adjust it. Subtracting two datetime.now() values may therefore be wrong, or even negative. To time an operation, use a monotonic clock, which only moves forward.
import time
start = time.monotonic()
sum(range(1_000_000))
elapsed = time.monotonic() - start
print(f"Took {elapsed:.4f} seconds")Use time.monotonic() or time.perf_counter() for durations within one process. Use aware datetimes or timestamps for recording when something happened. The values from time.monotonic() have no meaning outside the running process, so never store them.
Summary of rules
- Call
datetime.now(timezone.utc)when you need "now" as a stored value. - Convert timestamps with an explicit
tzargument. - Never call
.timestamp()on a naive datetime. - Use a monotonic clock to measure elapsed time.
Exercise
A colleague writes datetime.fromtimestamp(1_700_000_000_000, tz=timezone.utc) with a timestamp from a JavaScript front end, and the call fails or returns a nonsensical year. What is wrong, and what is the fix?
Show answer
JavaScript timestamps are in milliseconds, but fromtimestamp() expects seconds. The value is 1000 times too large. Divide by 1000: datetime.fromtimestamp(1_700_000_000_000 / 1000, tz=timezone.utc). This gives 2023-11-14 22:13:20+00:00.
Exercise
Why can datetime(2026, 1, 1).timestamp() return different numbers on two machines, and how do you make it consistent?
Show answer
The datetime is naive, so Python interprets it in each machine's local time zone. Attach a zone first, for example datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp(). The result is then the same everywhere.