Mock datetime with time-machine in Python
Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().
Requires third-party packages — install first
pip install time-machine
Python code
11 linesfrom time_machine import travel
from datetime import datetime
@travel("2020-01-01 10:30:00")
def check_date():
return datetime.utcnow()
if __name__ == "__main__":
print(check_date())
Output
2020-01-01 10:30:00
How it works
The @travel decorator shifts the system time for the decorated function's execution. Inside check_date, datetime.utcnow() returns the mocked time instead of the real current time. This is a lightweight alternative to freezegun and supports Python's datetime module directly. The mock is automatically restored after the function exits.
Common mistakes
- Forgetting to install time-machine with pip install time-machine
- Using datetime.now() instead of datetime.utcnow() and expecting UTC
- Applying the decorator to the wrong scope — it must wrap the function that checks the time
- Not accounting for timezone-aware code that uses timezone.utc
Variations
- Use `@travel('2020-01-01 10:30:00', tz_offset=0)` for timezone-explicit tests
Real-world use cases
- Writing unit tests for code that logs timestamps, ensuring deterministic output.
- Validating date-handling logic without waiting for a specific real time to arrive.
- Reproducing a time-sensitive bug by freezing the clock to the exact moment it occurs.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.