time-machine

3.2.0 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

Demonstrates `time-machine` as a decorator and context manager to fix the current time for testing.

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!")

view raw JSON →