Miscellaneous

This section contains API documentation for miscellaneous functions and data

Context managers

whenever.patch_current_time(
dt: Instant | ZonedDateTime | OffsetDateTime,
/,
*,
keep_ticking: bool,
) → Iterator[TimePatch][source]

Patch the current time as whenever sees it, for testing. A frozen patch (keep_ticking=False) holds one instant; a ticking patch (keep_ticking=True) advances from it. Works as a context manager or as a decorator. Patches do not nest: creating one while another is active raises RuntimeError. The decorator form does not pass the handle to the decorated function, and doesn’t cover the body of an async def or generator function: enter with patch_current_time(...) inside the function instead.

Important

  • This function should be used only for testing purposes.

  • This function only affects whenever’s now functions. It does not affect the standard library’s time functions or any other libraries. Use the time_machine package if you also want to patch other libraries.

  • It doesn’t affect the system time zone. If you need to patch the system time zone, set the TZ environment variable in combination with reset_system_tz().

Example

>>> from whenever import Instant, patch_current_time, seconds
>>> i = Instant.from_utc(1980, 3, 2, hour=2)
>>> with patch_current_time(i, keep_ticking=False) as p:
...     assert Instant.now() == i
...     p.shift(hours=4)
...     assert i.now() == i.add(hours=4)
...
>>> assert Instant.now() != i
...
>>> @patch_current_time(i, keep_ticking=True)
... def test_thing():
...     assert (Instant.now() - i) < seconds(1)
class whenever.TimePatch(*args, **kwargs)[source]

The handle to an active time patch: move the patched clock with shift() or move_to().

move_to(value: Instant | OffsetDateTime | ZonedDateTime, /) → None[source]

Move the patched clock to an exact time.

shift(
delta: TimeDelta = ...,
/,
*,
weeks: float = 0,
days: float = 0,
hours: float = 0,
minutes: float = 0,
seconds: float = 0,
milliseconds: float = 0,
microseconds: float = 0,
nanoseconds: int = 0,
days_assumed_24h_ok: bool = False,
) → None[source]

Move the patched clock by an elapsed time, given as a TimeDelta or as the keywords of Instant.add(). days= and weeks= count 24-hour days and warn with DaysAssumed24HoursWarning unless days_assumed_24h_ok=True. A ticking patch shifts from the current instant.

System time zone

whenever.SYSTEM_TZ

A public sentinel that requests the system time zone. Pass it where a named time zone is accepted to resolve the system time zone at call time: the ZonedDateTime constructor, now(), today(), replace(), to_tz(), and assume_tz(). The returned datetime stores the resolved time zone, not the sentinel itself. A system time zone that cannot be resolved raises TimeZoneNotFoundError.

See The system time zone for caching, reset behavior, and system time zones without a time zone ID.

Time zone data

whenever.get_tzpath() → tuple[str, ...][source]

The time zone search path: the directories in which whenever looks for time zone data, in order. The tuple is a snapshot: it does not change when reset_tzpath() is called later.

whenever.TZPATH

Deprecated: use get_tzpath(). Removed in 1.0.

whenever.clear_tzcache(*, only_keys: Iterable[str] | None = None) → None[source]

Clear the time zone cache. With only_keys, clear only the entries for those time zone IDs, matched case-insensitively; an ID that is not cached is a no-op.

Caution

Calling this function may change the behavior of existing ZonedDateTime instances in surprising ways. Most significantly, strict_eq() may return False between two time zone instances with the same time zone ID, if this time zone definition was changed on disk.

Use this function only if you know that you need to.

Behaves similarly to zoneinfo.ZoneInfo.clear_cache().

Raises:

TypeError – If only_keys is a single string or not an iterable of strings.

whenever.reset_tzpath(target: Sequence[str | PathLike[str]] | None = None, /) → None[source]

Set the time zone search path: the directories in which whenever looks for time zone data, in order. Each entry is an absolute path, as a str or a path-like object. Without an argument, the path is read again from the PYTHONTZPATH environment variable, falling back to the interpreter’s compiled-in default, as zoneinfo.reset_tzpath() does.

It does not affect the zoneinfo module or other libraries.

Note

Due to caching, looking up a time zone after changing the search path may continue to use the already loaded definition. Call clear_tzcache() to make subsequent lookups load from the new path.

Raises:
  • TypeError – If the argument is not a list or tuple of paths.

  • ValueError – If an entry is not an absolute path.

whenever.available_timezones() → set[str][source]

Gather the set of all available time zone IDs.

Each call recalculates the set from the current time zone search path (see get_tzpath()) and the tzdata package, when it is installed. The special entries posixrules and localtime are excluded, as are the posix/ and right/ directories.

Warning

This function may open a large number of files, since the first few bytes of time zone files must be read to determine if they are valid.

Note

On the same time zone search path, the result equals zoneinfo.available_timezones() minus localtime.

whenever.reset_system_tz() → None[source]

Determine the system time zone again and cache it, replacing the cached one. An empty TZ environment variable means UTC.

>>> os.environ["TZ"] = "America/New_York"
>>> reset_system_tz()  # the system time zone is now New York
>>> os.environ["TZ"] = "Europe/London"
>>> ZonedDateTime.now(SYSTEM_TZ)  # still the cached New York time zone
ZonedDateTime("2025-06-18 15:11:08-04:00[America/New_York]")
>>> reset_system_tz()  # the system time zone is now London
>>> ZonedDateTime.now(SYSTEM_TZ)
ZonedDateTime("2025-06-18 20:11:08+01:00[Europe/London]")
Raises:

TimeZoneNotFoundError – If the system time zone cannot be resolved; the cached one stays.