Recipe 15.2 · Python
UTC, DateTimeOffset and a Testable Clock
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Code calls DateTime.Now in hundreds of places. In the archive, roughly 20,000 hand-written C# files (19,999, or 4.6%) use DateTime.Now, in 33 of the 35 engagements with C# code. Timestamps are stored in server local time, so when the database moves to a server in another region, or the clocks change in March, the data becomes ambiguous. Tests that depend on the current time either fail at midnight or are not written at all.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
DateTime.Now is the server's wall clock. During the autumn daylight saving change the same local hour happens twice, so a token created at 1:50 a.m. can appear valid for an extra hour. Move the app to a container running in UTC and every stored value is now off by several hours relative to the old ones. And there is no way to test the expiry without waiting thirty minutes.
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Password-reset token that uses server local time and cannot be tested
Source: ImproveCode, Chapter 15, Recipe 15.2 "UTC, DateTimeOffset and a Testable Clock"
Section: The way it's often written
Book page: 329 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
DateTime.Now becomes naive datetime.now(); Guid.NewGuid() becomes uuid.uuid4().
"""
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta
# Not to copy: local time, no offset, no way to test.
@dataclass
class User:
reset_token: str | None = None
reset_expires: datetime | None = None
class ResetTokenService:
def create(self, user: User) -> None:
user.reset_token = str(uuid.uuid4())
user.reset_expires = datetime.now() + timedelta(minutes=30)
self.save(user) # column type: datetime
def is_valid(self, user: User) -> bool:
return datetime.now() < user.reset_expires # type: ignore[operator]
def save(self, user: User) -> None:
...
The improved recipe
Register the real clock once:
And test with a fake one. This uses the Microsoft.Extensions.TimeProvider.Testing package and works with any test framework:
Requirements: Python 3.12+. Install: pip install fastapi
"""Register the system clock and reset-token policy for injection
Source: ImproveCode, Chapter 15, Recipe 15.2 "UTC, DateTimeOffset and a Testable Clock"
Section: The improved recipe
Book page: 329 -- original C# listing
Converted from C# to Python.
ASP.NET Core DI registration becomes FastAPI dependency providers: a singleton clock
and a per-request ResetTokenPolicy (tests can swap the clock via dependency_overrides).
"""
from typing import Annotated
from fastapi import Depends
from p329_r15_2_reset_token_policy_clock import Clock, ResetTokenPolicy, SystemClock
_SYSTEM_CLOCK = SystemClock()
def get_clock() -> Clock: # AddSingleton(TimeProvider.System)
return _SYSTEM_CLOCK
def get_reset_token_policy( # AddScoped<ResetTokenPolicy>()
clock: Annotated[Clock, Depends(get_clock)],
) -> ResetTokenPolicy:
return ResetTokenPolicy(clock)
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Reset-token policy with UTC expiry and an injectable clock
Source: ImproveCode, Chapter 15, Recipe 15.2 "UTC, DateTimeOffset and a Testable Clock"
Section: The improved recipe
Book page: 329 -- original C# listing
Converted from C# to Python.
TimeProvider becomes a small Clock Protocol with a SystemClock implementation;
DateTimeOffset becomes a timezone-aware datetime in UTC.
"""
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Protocol
class Clock(Protocol):
def get_utc_now(self) -> datetime: ...
class SystemClock:
def get_utc_now(self) -> datetime:
return datetime.now(UTC)
@dataclass(frozen=True)
class ResetToken:
expires_at_utc: datetime
class ResetTokenPolicy:
_LIFETIME = timedelta(minutes=30)
def __init__(self, clock: Clock) -> None:
self._clock = clock
def issue(self) -> ResetToken:
return ResetToken(self._clock.get_utc_now() + self._LIFETIME)
def is_expired(self, token: ResetToken) -> bool:
return self._clock.get_utc_now() >= token.expires_at_utc
Requirements: Python 3.12+. Standard library only, nothing to install.
"""Test reset-token expiry with a fake clock advanced by hand
Source: ImproveCode, Chapter 15, Recipe 15.2 "UTC, DateTimeOffset and a Testable Clock"
Section: The improved recipe
Book page: 330 -- original C# listing
Converted from C# to Python.
FakeTimeProvider becomes a tiny FakeClock class; InvalidOperationException becomes
AssertionError so the function also works as a pytest test.
"""
from datetime import UTC, datetime, timedelta
from p329_r15_2_reset_token_policy_clock import ResetToken, ResetTokenPolicy
class FakeClock:
def __init__(self, start: datetime) -> None:
self._now = start
def get_utc_now(self) -> datetime:
return self._now
def advance(self, delta: timedelta) -> None:
self._now += delta
def test_token_expires_after_thirty_minutes() -> None:
clock = FakeClock(datetime(2026, 11, 1, 5, 50, 0, tzinfo=UTC))
policy = ResetTokenPolicy(clock)
token: ResetToken = policy.issue()
clock.advance(timedelta(minutes=29))
if policy.is_expired(token):
raise AssertionError("Expired early.")
clock.advance(timedelta(minutes=1))
if not policy.is_expired(token):
raise AssertionError("Did not expire.")
How it works
TimeProvider is an abstract class in the base library since .NET 8. TimeProvider.System returns the real clock; GetUtcNow() returns a DateTimeOffset with a zero offset. Because the class receives the clock through its constructor, nothing in it reads the machine time directly, and a test can set the time to any instant, including the night the clocks change.
Before .NET 8 every team wrote its own IClock or ISystemClock interface. If you have one, keep it or make it a thin adapter over TimeProvider; the important part is that business code asks for the time instead of grabbing it.
DateTimeOffset carries its offset from UTC, so a value can never be misread as local time. I use it for every instant: when something happened or when something expires. DateTime is still fine when the value really is local and unattached to a moment, such as a store's opening time, and DateOnly is right for birthdays, due dates and business days.
On the SQL Server side, store instants as datetime2(3) holding UTC, with a name that says so (CreatedUtc), or as datetimeoffset(3). Use SYSUTCDATETIME() for defaults instead of GETDATE(), which returns the server's local time.
Variations and pitfalls
DateTime.UtcNowis still better thanDateTime.Nowwhen you can't inject a clock, for example in a static field initializer. It's the first fix to make in old code.- Don't call
ToLocalTime()on a web server. The server's time zone is not the user's. Convert for display with an explicit zone, as in the next recipe. FakeTimeProvideralso drives timers andTask.Delay(TimeSpan, TimeProvider), which makes retry and timeout code testable too.- When reading
datetimecolumns with ADO.NET you getDateTimeKind.Unspecified. If the column holds UTC, callDateTime.SpecifyKind(value, DateTimeKind.Utc)at the data boundary so the kind is right everywhere else.
On .NET Framework
TimeProvider is available for .NET Framework 4.6.2 and later through the Microsoft.Bcl.TimeProvider package, so you can introduce the same abstraction in a 4.8 application before migrating it.