Freezegun is a Python library designed to freeze time during code execution, great for testing time-dependent functionality.

Its primary utility lies in mocking the current time returned by Python’s datetime.datetime.now() and related functions.

By freezing time, Freezegun enables you to simulate various points in time without affecting the actual advancement of the system clock.

pip install freezegun

from freezegun import freeze_time

def get_greeting():

current_time = datetime.now()

if current_time.hour < 12:

return “Good morning!”

elif 12 current_time.hour < 18:

return “Good afternoon!”

else:

return “Good evening!”

# Test case with frozen time using freezegun

@freeze_time(“2023-01-01 12:00:00”)

def test_get_greeting_frozen_time():

# This test will always use the frozen time, so the result is predictable

greeting = get_greeting()

assert greeting == “Good afternoon!”