Using freezegun to Mock and Freeze Time in Python Tests
freezegun is a Python library that lets developers mock and freeze the current time, enabling precise control over time‑dependent code during unit testing, with examples covering basic usage, timezone handling, complex datetime objects, and dynamic time manipulation.
freezegun is a Python library that allows you to mock and freeze time, which is essential for testing time‑sensitive logic.
Use cases include testing functions with time‑dependent logic such as scheduled tasks, expiration checks, holiday calculations, cache expiration, server responses based on the current date, and periodic reports or email triggers.
Basic usage example:
from freezegun import freeze_time
from datetime import datetime
@freeze_time("2023-01-01")
def test_current_datetime():
now = datetime.now()
assert now.year == 2023
assert now.month == 1
assert now.day == 1
test_current_datetime()Freezing time within a context:
def test_scheduled_event():
with freeze_time("2024-12-25"):
is_christmas = is_special_day()
assert is_christmas is TrueFreezing a specific timezone:
from freezegun.api import freeze_time
from pytz import timezone
@freeze_time("2025-07-04", tz_offset=-4) # US Eastern Daylight Time
def test_us_independence_day():
eastern_time = datetime.now(timezone('US/Eastern'))
assert eastern_time.month == 7
assert eastern_time.day == 4Freezing complex datetime objects:
from datetime import timedelta, datetime
from freezegun import freeze_time
@freeze_time("2026-01-01 12:00:00")
def test_timedelta_addition():
start_time = datetime.now()
future_time = start_time + timedelta(hours=1)
assert future_time.hour == 13
assert future_time.minute == 0
assert future_time.second == 0Dynamic time changes:
def test_dynamic_freeze():
freezer = freeze_time("2027-01-01")
with freezer:
assert datetime.now().year == 2027
freezer.move_to("2028-01-01")
with freezer:
assert datetime.now().year == 2028These examples demonstrate how freezegun can precisely control time points in your code, improving test coverage and determinism. Remember to install the freezegun package and adapt the examples to your specific testing needs.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.