Sub topic 5
Getting the current time and working with timestamps
This chapter assumes you know the datetime and timezone types from earlier chapters, and the difference between naive and aware datetimes. You should also know that UTC is the reference time that has no daylight saving. Here you will learn how to read the clock correctly, how POSIX timestamps relate to datetimes, and where the usual mistakes are.
Reading the current time
Python gives you several ways to ask "what time is it?". They differ in what type they return and whether the result carries a time zone.
| Call | Returns | Aware? | Notes |
|---|---|---|---|
| `datetime.now(timezone.utc)` | `datetime` | Yes | The recommended default for storing and comparing |
| `datetime.now(ZoneInfo("Asia/Tokyo"))` | `datetime` | Yes | Current time in a named zone |
| `datetime.now()` | `datetime` | No | Local wall-clock time of the machine, with no zone attached |
| `datetime.today()` | `datetime` | No | Same as `datetime.now()` without arguments |
| `datetime.utcnow()` | `datetime` | No | UTC values in a naive object. Deprecated since Python 3.12 |
| `time.time()` | `float` | n/a | Seconds since the epoch |
| `time.time_ns()` | `int` | n/a | Nanoseconds since the epoch |
| `time.monotonic()` | `float` | n/a | Seconds from an arbitrary start, never goes backwards |
The rule of thumb is to pass a tzinfo to now() every time. A call such as datetime.now(timezone.utc) produces an object that knows what instant it describes. A call such as datetime.now() produces a naive object that only makes sense on the machine that created it.
Why `utcnow()` is a trap
datetime.utcnow() looks like it does the right thing. The problem appears when you use its result:
from datetime import datetime, timezone
naive_utc = datetime.utcnow() # naive, but the fields are UTC
aware_utc = datetime.now(timezone.utc) # aware
# Naive values are assumed to be local time by timestamp(),
# so this is wrong on any machine whose zone is not UTC.
print(naive_utc.timestamp() - aware_utc.timestamp())On a machine set to UTC the printed difference is close to 0.0. On a machine at UTC+9 it is about -32400.0, because timestamp() treats the naive value as local time and subtracts nine hours. The code runs without an error and gives a wrong answer, which is why this mistake survives in production.
What a POSIX timestamp is
A POSIX timestamp (also called Unix time or epoch time) counts the seconds since the epoch, which is 1970-01-01 00:00:00 UTC. It has three properties that matter:
- It is zone-free. A timestamp names one instant. Two people in different zones see the same number.
- It ignores leap seconds. Every day is treated as exactly 86,400 seconds, so the timestamp is not a count of physically elapsed seconds.
- It can be negative for instants before 1970.
from datetime import datetime, timezone
print(datetime.fromtimestamp(0, tz=timezone.utc))
print(datetime.fromtimestamp(1_700_000_000, tz=timezone.utc))
print(datetime(2000, 1, 1, tzinfo=timezone.utc).timestamp())This prints:
1970-01-01 00:00:00+00:00
2023-11-14 22:13:20+00:00
946684800.0Converting between datetimes and timestamps
The two directions are datetime.timestamp() and datetime.fromtimestamp(). The following example gets the current time as an aware UTC datetime, converts it to a timestamp, and converts it back.
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. For present-day values, a float has enough precision to hold microseconds, and fromtimestamp() rounds to the nearest microsecond. For this reason the round trip is exact.
The `tz` argument decides the result type
fromtimestamp() behaves differently depending on whether you pass tz:
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(ts).tzinfo)The first two lines print 2023-11-14 22:13:20+00:00 and 2023-11-15 07:13:20+09:00. They describe the same instant. The third line prints None, because without tz you get a naive datetime in the machine's local zone. That value depends on the server's configuration, so avoid it in any code that runs on more than one machine.
`timestamp()` on a naive datetime
When you call timestamp() on a naive datetime, Python assumes the fields are local time. It then asks the operating system for that zone's offset. This causes two problems:
- The result changes when the same code runs on a machine with a different
TZsetting. - If the local time falls in a daylight saving gap or fold, the result depends on the
foldattribute, which the daylight saving chapter covers.
With an aware datetime, timestamp() is a pure calculation with no dependence on the machine.
Precision, range, and exact integer math
A timestamp from time.time() is a 64-bit float. At present-day magnitudes (about 1.7 billion seconds) the spacing between adjacent floats is about 240 nanoseconds. That is finer than a datetime, which stores microseconds, so a single conversion is safe. Problems appear when you do repeated arithmetic on floats, or when you use values far from 1970.
If you need exact integer seconds, avoid floats and use timedelta division:
from datetime import datetime, timedelta, timezone
EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
def to_epoch_seconds(dt: datetime) -> int:
"""Whole seconds since the epoch, rounded down. dt must be aware."""
return (dt - EPOCH) // timedelta(seconds=1)
def from_epoch_millis(ms: int) -> datetime:
"""Convert integer milliseconds (as JavaScript's Date.now() gives) to an aware UTC datetime."""
return EPOCH + timedelta(milliseconds=ms)
print(to_epoch_seconds(datetime(2000, 1, 1, tzinfo=timezone.utc)))
print(from_epoch_millis(1_700_000_000_123))This prints:
946684800
2023-11-14 22:13:20.123000+00:00Subtracting an aware datetime from another aware datetime gives a timedelta. Dividing one timedelta by another with // gives an integer, and no float is involved. The subtraction raises a TypeError if dt is naive, which is the behavior you want here.
A few edge cases to keep in mind:
- Milliseconds and microseconds. JavaScript, Java, and many databases use milliseconds. Passing
1_700_000_000_123straight tofromtimestamp()fails or gives a date thousands of years away. Divide by 1000 or use thetimedeltaapproach above. - Range limits.
datetimesupports years 1 to 9999, butfromtimestamp()also depends on the platform's C library. Very large or negative values can raiseOverflowError,OSError, orValueError. On Windows, negative timestamps are not supported for local-time conversions. ComputingEPOCH + timedelta(seconds=ts)avoids those platform limits for aware UTC values. - Leap seconds. A
datetimecannot represent second 60, so Python never shows a leap second. Treat timestamps as "seconds on a smoothed clock", not as a physical stopwatch.
Measuring elapsed time: do not use the wall clock
The wall clock (datetime.now() and time.time()) can jump. NTP can correct it, an administrator can change it, and a virtual machine can resume with a stale value. If you subtract two wall-clock readings you can get a negative duration or a wrong one. For elapsed time, use a monotonic clock:
import time
start = time.perf_counter()
time.sleep(0.1)
elapsed = time.perf_counter() - start
print(f"{elapsed:.1f} seconds")This prints about 0.1 seconds. The two functions differ as follows:
time.monotonic()is meant for timeouts and deadlines in long-running programs.time.perf_counter()has the highest available resolution and suits benchmarking.
Neither value has a meaning on its own. Only the difference between two readings from the same function is useful, and you cannot convert it to a calendar date.
Making time testable
Code that calls datetime.now() directly is hard to test, because its result changes on every run. A common fix is to pass the clock in as a parameter. The function below takes an optional now callable that defaults to the real clock.
from collections.abc import Callable
from datetime import datetime, timedelta, timezone
def utc_now() -> datetime:
return datetime.now(timezone.utc)
def is_expired(expires_at: datetime, now: Callable[[], datetime] = utc_now) -> bool:
return now() >= expires_at
expires = datetime(2026, 11, 26, 12, 0, tzinfo=timezone.utc)
before = lambda: expires - timedelta(minutes=1)
after = lambda: expires + timedelta(minutes=1)
print(is_expired(expires, now=before))
print(is_expired(expires, now=after))This prints False and then True, on every run and on every machine. Both datetimes are aware, so the comparison cannot raise a TypeError, and it is correct no matter what the machine's zone is.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Timestamps are off by a whole number of hours on some servers | `timestamp()` called on a naive datetime, or `utcnow()` used | Create aware datetimes with `now(timezone.utc)` |
| `TypeError: can't compare offset-naive and offset-aware datetimes` | One value came from `now()` with no argument | Make both sides aware |
| Date in the year 50000 or an `OverflowError` | A millisecond value was passed as seconds | Divide by 1000, or add a `timedelta(milliseconds=...)` to the epoch |
| Negative or zero elapsed time | Subtracting wall-clock readings across a clock adjustment | Use `time.monotonic()` or `time.perf_counter()` |
| `DeprecationWarning` on Python 3.12 or later | `utcnow()` or `utcfromtimestamp()` | Pass `timezone.utc` to `now()` or `fromtimestamp()` |
Exercise
A web API returns the integer 1700000000123 in a field named created_ms. Write one expression that turns it into an aware UTC datetime without using floats. Then say what datetime.fromtimestamp(1700000000123, tz=timezone.utc) would do and why you should not use it.
Show answer
Use datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(milliseconds=1700000000123), which gives 2023-11-14 22:13:20.123000+00:00 and does all the arithmetic with integers. Passing the value directly to fromtimestamp() treats it as seconds, so it describes a date tens of thousands of years in the future. That is beyond year 9999, so Python raises an error such as ValueError: year 55832 is out of range or OverflowError, depending on the platform. The unit mismatch is the cause.
Exercise
A script records start = datetime.now() and end = datetime.now() around a slow job, and prints end - start. Last night it reported a negative duration. Give a likely cause, and rewrite the timing with the right clock.
Show answer
The wall clock moved backwards between the two readings, for example because NTP corrected it or the system clock was adjusted. A naive local datetime.now() is also affected by daylight saving changes, which shift the local clock by an hour. The fix is start = time.monotonic(), then elapsed = time.monotonic() - start after the job. A monotonic clock never goes backwards, so the difference cannot be negative. If you also need a calendar timestamp for a log line, record datetime.now(timezone.utc) separately and do not use it for the duration.