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.
pip install time-machineVerified import paths — ran on the pinned version, not inferred.
Demonstrates `time-machine` as a decorator and context manager to fix the current time for testing.
Be aware of the global nature of time mocking in multithreaded or asynchronous tests. Design tests to isolate time-sensitive operations or use careful synchronization.
For external systems, mock the external system's responses directly rather than relying on `time-machine`.
Ensure your testing environment uses CPython if `time-machine` is a dependency.
If you need to mock `time.monotonic()` or `time.monotonic_ns()`, use `unittest.mock` or a similar patching mechanism manually, but be aware of potential side effects.
Update `time_machine.travel` calls to pass a timezone-aware `datetime` object (e.g., `dt.datetime(..., tzinfo=ZoneInfo('America/Los_Angeles'))`) instead of `tz_offset`.Set `time_machine.naive_mode = time_machine.LOCAL` or `time_machine.naive_mode = time_machine.ERROR` in your test setup to enforce a consistent interpretation.
Ensure that `freezegun` is not active in the same process where `time-machine` is being used. If migrating, use the provided `time_machine migrate` CLI tool.
Ensure development tools and Python development headers are installed for your operating system (e.g., `sudo apt-get install build-essential python3-dev` on Debian/Ubuntu, or Xcode command line tools on macOS).
Use `import time_machine` instead.
Provide a valid destination like a datetime string, a `datetime` object, `date` object, or a float timestamp, e.g., `time_machine.travel('2023-01-01')`.Ensure the `destination` argument is one of the supported types, for example, `'2024-01-01 10:00:00'` or `datetime.datetime(2024, 1, 1, 10, 0, 0)`.
Provide a valid, unambiguous date or datetime string, such as `'YYYY-MM-DD'`, `'YYYY-MM-DD HH:MM:SS'`, or an ISO 8601 formatted string.