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.
pip install freezegun
Python code
13 linesfrom 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
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
- Use `with freeze_time("2024-01-15 12:30:00"):` as a context manager instead of a decorator for finer control
- 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
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.