How to freeze time in Python tests with freezegun

Use the freezegun decorator to freeze datetime.now() at a fixed timestamp so tests that depend on current time run deterministically.

Easy Python 3.8+ Aug 9, 2026 Testing & modern typing 15 views 0 copies

Requires third-party packages — install first
pip install freezegun

Python code

13 lines
Python 3.8+
from datetime import datetime
from freezegun import freeze_time


@freeze_time("2024-01-15 12:30:00")
def test_frozen_time():
    now = datetime.now()
    return now


if __name__ == "__main__":
    result = test_frozen_time()
    print(result)

Output

stdout
2024-01-15 12:30:00

How it works

The @freeze_time decorator patches datetime.now() (and other time-related functions) inside the wrapped function's scope. When test_frozen_time runs, datetime.now() returns the fixed timestamp instead of the real current time. The decorator automatically restores the real time after the function exits, so you don't need manual cleanup. This makes assertions about time-dependent behavior reliable and repeatable across runs.

Common mistakes

  • Forgetting that `freeze_time` only affects code executed inside the decorated function — not global state
  • Using a naive datetime string without timezone when the code under test expects aware datetimes
  • Nesting `freeze_time` without understanding that inner scopes override outer ones
  • Assuming `freeze_time` patches `time.time()` — it does, but only when called from inside the decorated scope

Variations

  1. Use `with freeze_time("2024-01-15 12:30:00"):` as a context manager instead of a decorator for finer control
  2. Pass a `datetime` object directly, e.g. `@freeze_time(datetime(2024, 1, 15, 12, 30))`

Real-world use cases

  • Unit-testing billing logic that computes daily or monthly charges based on `date.today()`.
  • Verifying retry/backoff timers in a background job without waiting the actual sleep interval.
  • Making snapshot-style regression tests for logs or reports that embed timestamps deterministic.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.