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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Python code

11 lines
Python 3.9+
from 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

stdout
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

  1. Use `freezegun` library's `freeze_time` decorator for a simpler, more readable approach.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.