time-machine
time-machine is a Python library that enables 'time travel' in your tests by mocking Python's standard library functions that return the current date or datetime. It achieves this efficiently using C extensions, providing a fast and robust solution for time-dependent testing. The library is actively maintained, with version 3.2.0 released in December 2025.
Warnings
- gotcha Time is a global state. When mocking time with `time-machine`, all concurrent threads or asynchronous functions within the same process will also be affected. This can lead to unexpected behavior if not accounted for.
- gotcha `time-machine` only mocks Python's standard library functions for time. It does not affect other processes (e.g., database servers, external APIs) or libraries that make direct C-level system calls for time.
- gotcha `time-machine` currently only works with CPython (the standard Python interpreter) and is not compatible with other Python interpreters like PyPy.
- breaking As of version 3.0.0, `time-machine` no longer mocks `time.monotonic()` and `time.monotonic_ns()`. Mocking these functions caused significant issues with asyncio event loops, test duration measurements, and other libraries relying on a strictly monotonic clock.
- breaking The `tz_offset` argument for specifying timezones was removed in version 2.0.0. Timezones should now be specified by providing a `datetime` object with a `zoneinfo.ZoneInfo` instance attached (Python 3.9+ or `backports.zoneinfo`).
- gotcha The default `naive_mode` for interpreting naive datetimes is `MIXED`, which can be confusing (naive `datetime` objects are UTC, strings are local). It's recommended to explicitly set `naive_mode` to `LOCAL` or `ERROR` for consistent and clearer behavior.
- gotcha Attempting to start time travel with `time-machine` when `freezegun` (another time-mocking library) is already active will raise a `RuntimeError` to prevent conflicts and ensure a clean state for mocking.
Install
-
pip install time-machine
Imports
- travel
from time_machine import travel
- is_travelling
from time_machine import is_travelling
- naive_mode
from time_machine import naive_mode
Quickstart
import datetime as dt
import time_machine
@time_machine.travel("1955-11-05 01:22")
def test_delorean():
assert dt.date.today().isoformat() == "1955-11-05"
def use_context_manager():
with time_machine.travel(dt.datetime(1985, 10, 26, 1, 24, tzinfo=dt.timezone.utc)):
assert dt.datetime.now(dt.timezone.utc).year == 1985
# To run the example (in a test framework like pytest, this would be automatic):
if __name__ == "__main__":
test_delorean()
use_context_manager()
print("Quickstart example ran successfully!")