Skip to content

xtr_clock

A clock an application can be handed, instead of the one it is standing on.

Reading the time is an input like any other, and code that reaches for the operating system to get it cannot be told what time it is. That is what makes a test about expiry, backoff or a billing period slow, flaky, or quietly wrong every March.

Depend on :class:~xtr_clock.clock_interface.ClockInterface and the choice becomes a constructor argument: :class:~xtr_clock.system_clock.SystemClock in production, :class:~xtr_clock.monotonic_clock.MonotonicClock where a duration must be trusted, :class:~xtr_clock.mock_clock.MockClock in a test. What comes back is always a :class:~xtr_clock.date_point.DatePoint: a :class:~datetime.datetime that is always timezone-aware and stays itself through every operation.

Code that cannot be handed anything asks :meth:~xtr_clock.clock.Clock.get, and a test answers with :func:~xtr_clock.testing.mock_time.

Nothing here depends on anything outside the standard library.

Clock

Clock(clock: SupportsNow | None = None, timezone: str | tzinfo | None = None)

The clock in force, and a clock that reads it.

As a class it is the registry: :meth:get answers with whatever clock is in force, :meth:set installs one for good, :meth:using installs one for a scope.

As an instance it is a clock in its own right, and a useful one twice over. Built around an object that can only say :meth:~SupportsNow.now, it fills in the rest of the contract. Built around nothing, it forwards to whatever is in force at the moment each question is asked — so a class handed one at startup reads a clock a test installs later.

Prefer taking a :class:~xtr_clock.clock_interface.ClockInterface as a constructor argument. Reach for this only where nothing can be handed in.

Wrap clock, or the clock in force when none is given.

Parameters:

  • clock (SupportsNow | None, default: None ) –

    The clock to read. None reads whichever clock is in force each time a question is asked, rather than the one in force now.

  • timezone (str | tzinfo | None, default: None ) –

    A zone to pin every reading to. None reports instants in whatever zone the wrapped clock used.

Raises:

timezone property

timezone: tzinfo | None

The zone readings are pinned to, or None to follow the clock read.

get classmethod

get() -> ClockInterface

Return the clock in force.

A scope opened by :meth:using wins; otherwise whatever :meth:set installed; otherwise a :class:~xtr_clock.system_clock.SystemClock, built once and kept.

set classmethod

set(clock: SupportsNow) -> None

Install clock as the clock in force, until something replaces it.

An object that only answers :meth:~SupportsNow.now is wrapped so it satisfies the whole contract.

Prefer :meth:using in a test: this one has no end, and a test that forgets to undo it hands the next one a clock it never asked for.

install classmethod

install(clock: SupportsNow) -> Callable[[], None]

Install clock until the returned function is called, which puts the previous back.

:meth:using for a lifetime that is not a with block — a kernel's, from boot to shutdown. Its end may run in another task or thread than its start, which a with block's may not.

Parameters:

  • clock (SupportsNow) –

    The clock to install. An object that only answers :meth:~SupportsNow.now is wrapped.

Returns:

  • Callable[[], None] –

    What puts back the clock that was in force; calling it again does

  • Callable[[], None] –

    nothing.

using classmethod

using(clock: SupportsNow) -> Generator[ClockInterface]

Install clock for the duration of a with block.

The previous clock comes back on the way out, including when the block raises. For the context it runs in, scopes nest exactly. The process-wide fallback a thread started later reads is the innermost block still open, whichever context opened it: blocks in concurrent tasks may end in any order.

Parameters:

  • clock (SupportsNow) –

    The clock to install. An object that only answers :meth:~SupportsNow.now is wrapped.

Yields:

now

now() -> DatePoint

Return the current instant, as the clock being read tells it.

sleep

sleep(seconds: float) -> None

Block for seconds, the way the clock being read does.

A clock that only answers :meth:~SupportsNow.now cannot say how to wait, so real time is what passes.

sleep_async async

sleep_async(seconds: float) -> None

Wait seconds the way the clock being read does, without blocking.

with_timezone

with_timezone(timezone: str | tzinfo) -> Self

Return the same clock pinning every reading to timezone.

Raises:

ClockAwareMixin

Gives a class a clock it can be handed, and a default until it is.

Taking a :class:~xtr_clock.clock_interface.ClockInterface as a constructor argument is still the clearest thing to do. This is for the case where you cannot: a class whose constructor is already spoken for by a framework, or a long-lived one you are making testable without rewriting every place that builds it.

It defines no __init__, so it composes with any class — including a dataclass — and reads the clock in force until :meth:set_clock says otherwise.

class TokenIssuer(ClockAwareMixin):
    def issue(self) -> Token:
        return Token(expires_at=self.now().modify("+1 hour"))


issuer = TokenIssuer()
issuer.set_clock(MockClock("2024-04-09 12:00:00"))

clock property

clock: ClockInterface

The clock this object reads: the one it was given, or the one in force.

set_clock

set_clock(clock: ClockInterface) -> None

Read time from clock from now on.

now

now() -> DatePoint

Return the current instant, according to this object's clock.

ClockInterface

Bases: SupportsNow, Protocol

The contract time-sensitive code should depend on.

Depend on this rather than on a concrete clock and the choice between reading the operating system, counting monotonically, and standing still for a test becomes a constructor argument.

Both a blocking and an awaitable wait live here rather than on separate contracts, because a clock that can only do one of them is a clock half the application cannot use — and the two cannot share a name, since one returns and the other is awaited.

now

now() -> DatePoint

Return the current instant, always timezone-aware.

sleep

sleep(seconds: float) -> None

Block for seconds, which a frozen clock does instantly.

A value of zero or less returns immediately.

sleep_async async

sleep_async(seconds: float) -> None

Wait seconds without blocking the event loop.

A value of zero or less returns immediately.

with_timezone

with_timezone(timezone: str | tzinfo) -> Self

Return the same clock reading its instants in another zone.

This one is left alone, so a class that pins a zone for itself does not change the time anybody else reads.

Raises:

SupportsNow

Bases: Protocol

Anything that can say what time it is.

Deliberately structural and deliberately minimal: a clock written against some other library, or a two-line stub in a test, satisfies it without importing anything from here. Hand one to :class:~xtr_clock.clock.Clock to get the full contract back.

now

now() -> datetime

Return the current instant.

DatePoint

Bases: datetime

A timezone-aware instant that survives every operation as itself.

now classmethod

now(tz: tzinfo | None = None) -> Self

Return the current instant, read from the clock in force.

This is the one method that departs from :meth:datetime.datetime.now: it asks :meth:~xtr_clock.clock.Clock.get rather than the operating system, so freezing the clock in a test reaches code that calls DatePoint.now() without having been handed a clock.

Parameters:

  • tz (tzinfo | None, default: None ) –

    The zone to read the instant in. None keeps whichever zone the clock answers in.

parse classmethod

parse(modifier: str, timezone: str | tzinfo | None = None, *, reference: datetime | None = None) -> Self

Return the instant modifier describes.

modifier is read by the grammar documented on :mod:xtr_clock.modifier: an offset like '+1 day', a keyword like 'tomorrow', an ISO-8601 datetime, a timezone name, or any of them with a zone trailing.

Parameters:

  • modifier (str) –

    The modifier to read.

  • timezone (str | tzinfo | None, default: None ) –

    The zone to read the reference in before applying modifier. A zone named inside it wins over this one.

  • reference (datetime | None, default: None ) –

    The instant modifier is relative to. Defaults to whatever the clock in force says now is.

Returns:

  • Self –

    The instant described.

Raises:

from_datetime classmethod

from_datetime(value: datetime) -> Self

Return value as a DatePoint.

A DatePoint is returned unchanged, so adopting one that already is costs nothing. A naive datetime is read as local time.

Parameters:

  • value (datetime) –

    The datetime to adopt.

modify

modify(modifier: str) -> Self

Return the instant modifier describes, relative to this one.

Parameters:

  • modifier (str) –

    A modifier the grammar on :mod:xtr_clock.modifier can read.

Returns:

  • Self –

    A new instant; this one is unchanged.

Raises:

with_timezone

with_timezone(timezone: str | tzinfo) -> Self

Return this same instant, read in another zone.

The moment does not move — only the wall clock showing it does.

Parameters:

  • timezone (str | tzinfo) –

    A name, an offset, or a resolved zone.

Raises:

to_naive_utc

to_naive_utc() -> datetime

Return this instant's UTC wall clock, as a plain naive datetime.

Some storage keeps an instant without a zone — a TIMESTAMP WITHOUT TIME ZONE column holding UTC — and its driver wants exactly a naive :class:~datetime.datetime: one refuses an aware value, another converts the offset it is handed, a third does not recognise a subclass at all. replace(tzinfo=None) does not give that value: it answers with a DatePoint the local zone was attached to again. This is the one reading that does.

A naive DatePoint — one built around this class's constructor — is read as local time, as this class reads every naive reading.

Returns:

  • datetime –

    A plain datetime, with no zone, holding the UTC wall clock of

  • datetime –

    this instant; fold is 0, since UTC repeats no hour.

Raises:

  • OverflowError –

    When the instant lies outside what datetime can hold in UTC — year 1 east of UTC, year 9999 west of it.

ClockError

Bases: Exception

Base class for every error raised by this library.

Catch this to handle anything reading a clock can go wrong with; catch a subclass to handle one cause. Every subclass carries the data a caller needs as typed attributes and composes its own message from them.

InvalidModifierError

InvalidModifierError(modifier: str, reason: str)

Bases: ClockError, ValueError

A modifier string the grammar cannot read.

Raised where the modifier is written rather than silently resolving to the current instant, so a typo in '+1 dya' is a failure and not a date that looks plausible.

Also a :class:ValueError, so code that already guards parsing with except ValueError keeps working without learning a new exception.

Attributes:

  • modifier (str) –

    The string that could not be read.

  • reason (str) –

    What about it could not be read.

Record the modifier that could not be read, and why.

InvalidTimezoneError

InvalidTimezoneError(timezone: str)

Bases: ClockError, ValueError

A timezone was named that this system cannot resolve.

Also a :class:ValueError, so code that already guards a conversion with except ValueError keeps working without learning a new exception.

Attributes:

  • timezone (str) –

    The name that could not be resolved.

Record the name that could not be resolved.

MockClock

MockClock(now: datetime | str | None = None, timezone: str | tzinfo | None = None)

Stands still, and moves only when asked.

Every reading is the same instant until :meth:sleep or :meth:modify moves it, which is what makes a test about duration — a token that expires in an hour, a retry that backs off, a report that covers a month — finish in no time and give the same answer on every machine, in every zone, on the last day of February.

Time it is told to sleep through passes at once, so a test never waits.

Where a real clock is built in the machine's own zone, this one defaults to UTC: a frozen test should not change its answer because the laptop that ran it is somewhere else.

Freeze at now.

Parameters:

  • now (datetime | str | None, default: None ) –

    Where to stand still. A datetime freezes exactly there and keeps its zone; a naive one is read in timezone, or UTC. A string is read by the grammar on :mod:xtr_clock.modifier against the clock currently in force, so '+1 day' composes with a clock already frozen. None freezes at the current instant.

  • timezone (str | tzinfo | None, default: None ) –

    The zone to report in. None keeps the zone now carried, or UTC when it carried none.

Raises:

timezone property

timezone: tzinfo

The zone this clock reports its instants in.

now

now() -> DatePoint

Return the instant this clock is frozen at.

The same object every time until the clock moves, which is safe because a :class:~xtr_clock.date_point.DatePoint is immutable.

sleep

sleep(seconds: float) -> None

Move forward by seconds at once; zero or less does nothing.

This is elapsed time, not a wall-clock offset, so sleeping through a daylight saving change lands where a real clock would.

sleep_async async

sleep_async(seconds: float) -> None

Move forward by seconds at once, yielding to the event loop.

Nothing is waited for, but control is handed back once so the tasks that were waiting on this clock get their turn — which is the whole behaviour a test of concurrent code is trying to observe.

modify

modify(modifier: str) -> None

Move to wherever modifier points, relative to right here.

Parameters:

  • modifier (str) –

    A modifier the grammar on :mod:xtr_clock.modifier can read — an offset, a keyword, or an absolute datetime.

Raises:

with_timezone

with_timezone(timezone: str | tzinfo) -> Self

Return a clock frozen at this same instant, read in another zone.

Raises:

MonotonicClock

MonotonicClock(timezone: str | tzinfo | None = None)

Counts from a counter that only ever moves forward.

A wall clock can jump: a daylight saving change, an administrator, a time daemon correcting a drift. Subtracting two readings taken either side of one of those gives a duration that is wrong, and occasionally negative. This clock is anchored to the wall clock once, when it is built, and from then on reports that anchor plus however much the machine's monotonic counter has advanced.

Use it for measuring elapsed time — a timeout, a rate limit, a span in a profile. Use :class:~xtr_clock.system_clock.SystemClock for recording when something happened, since this one drifts from the wall clock by exactly whatever correction it refused to follow.

Anchor to the wall clock now, then count from the monotonic one.

Parameters:

  • timezone (str | tzinfo | None, default: None ) –

    The zone instants are reported in. None uses the zone this machine is configured for.

Raises:

timezone property

timezone: tzinfo

The zone this clock reports its instants in.

now

now() -> DatePoint

Return the current instant, truncated to the microsecond.

sleep

sleep(seconds: float) -> None

Block for seconds; zero or less returns immediately.

sleep_async async

sleep_async(seconds: float) -> None

Wait seconds without blocking the event loop.

with_timezone

with_timezone(timezone: str | tzinfo) -> Self

Return the same clock reporting in timezone.

The anchor is carried over rather than taken again, so the copy and the original never disagree about what time it is.

Raises:

SystemClock

SystemClock(timezone: str | tzinfo | None = None)

Reads the time the operating system reports.

This is what an application runs on, and what :meth:~xtr_clock.clock.Clock.get falls back to when nothing else was installed. It follows the wall clock, so it moves when the machine's time is corrected — which is what you want for saying when something happened, and not what you want for measuring how long something took. Use :class:~xtr_clock.monotonic_clock.MonotonicClock for that.

Read the clock in timezone, or in the machine's own zone.

Parameters:

  • timezone (str | tzinfo | None, default: None ) –

    The zone instants are reported in. None uses the zone this machine is configured for.

Raises:

timezone property

timezone: tzinfo

The zone this clock reports its instants in.

now

now() -> DatePoint

Return the current instant.

sleep

sleep(seconds: float) -> None

Block for seconds; zero or less returns immediately.

sleep_async async

sleep_async(seconds: float) -> None

Wait seconds without blocking the event loop.

with_timezone

with_timezone(timezone: str | tzinfo) -> Self

Return the same clock reporting in timezone.

Raises:

shift_calendar

shift_calendar(moment: DateT, /, *, months: int = 0, days: int = 0) -> DateT

Move moment by whole months, then whole days, keeping the wall clock it shows.

"A month later" from the 31st lands on the last day of a shorter month, and "a day later" at 09:00 is at 09:00 again across a clock change — not 24 hours later. A wall clock the zone skipped over (the hour lost as the clocks go forward) is read as the instant it names, shown on the hour that replaced it, so the result always really existed.

Asked for no shift at all — a scheduler stepping a calendar by zero — it hands back what it was given, rather than resolving an instant it never moved.

apply_modifier

apply_modifier(reference: datetime, modifier: str) -> datetime

Return the instant modifier describes, read against reference.

Parameters:

  • reference (datetime) –

    The instant the modifier is relative to.

  • modifier (str) –

    One of the shapes documented on this module.

Returns:

  • datetime –

    The instant described, in the zone the modifier named or, when it

  • datetime –

    named none, in the zone reference already carried.

Raises:

local_timezone

local_timezone() -> tzinfo

Return the timezone this machine is configured for.

TZ wins when it names a zone this system knows, which is how a container is usually told where it lives. Otherwise the offset the operating system reports for the current instant is used — that is a fixed offset, so it carries the right wall clock now but knows nothing about the next daylight saving change.

A program that computes dates months out should name its zone rather than inherit this one.

resolve_timezone

resolve_timezone(timezone: str | tzinfo) -> tzinfo

Return timezone as a :class:~datetime.tzinfo.

A :class:~datetime.tzinfo is returned unchanged, so passing one already resolved costs nothing. A string is read as 'Z', a fixed offset like '+02:00' or '-0530', or an IANA name like 'Europe/Paris'.

Prefer an IANA name: a fixed offset cannot know when daylight saving starts, so a date six months away lands on the wrong wall clock.

Parameters:

  • timezone (str | tzinfo) –

    A name, an offset, or an already-resolved timezone.

Returns:

  • tzinfo –

    The resolved timezone.

Raises: