Mock datetime.now to freeze time in Python
Use unittest.mock.patch to replace datetime.now with a fixed value so your code always sees the same time during tests.
Python code
11 linesfrom datetime import datetime
from unittest.mock import patch
def current_message():
now = datetime.now()
return f"Current time: {now:%Y-%m-%d %H:%M:%S}"
if __name__ == "__main__":
with patch("__main__.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2024, 3, 15, 10, 30, 0)
print(current_message())
Output
Current time: 2024-03-15 10:30:00
How it works
The code patches __main__.datetime with unittest.mock.patch so any call to datetime.now() inside current_message() returns the fixed datetime instance. Because the patch is applied inside the with block, it only affects the execution within that scope. The function itself remains unchanged and still uses the real clock when called normally. This pattern is ideal for testing time-dependent logic without altering production code.
Common mistakes
- Patching the wrong module path (e.g. patching 'datetime.datetime' when the function imports datetime directly).
- Forgetting that `datetime` is used as a class, so `mock_dt.now.return_value` must be a datetime instance, not a string.
- Not restoring the real time after the test, causing order-dependent failures in test suites.
Variations
- Use `freezegun` library's `freeze_time` decorator for a simpler, more readable approach.
- Patch with `unittest.mock.patch.object(datetime, 'now', return_value=fixed_time)` when the module imports `from datetime import datetime`.
Real-world use cases
- Testing functions that generate timestamps, like logging messages or report filenames, to assert exact values.
- Simulating future or past dates in unit tests for features like subscription expiry or coupon validity.
- Creating deterministic fixtures for database timestamps when running integration tests.
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.