ZetCode

Python testing time-dependent code

last modified November 19, 2026 Python 3.15

In this article we test code that depends on the current time. A function that calls datetime.now returns different results at different times of day, so a test that passes in the morning fails in the evening. Expiry checks, retries with pauses, and reports for "yesterday" have the same problem.

There are two ways to make such code testable. We can pass the time, or a clock function, into the code, or we can replace the clock while the test runs: with unittest.mock from the standard library, or with the third-party time-machine and freezegun libraries. The examples build on the unittest and pytest tutorials and were run with the local time zone set to Europe/Bratislava.

$ pip install time-machine freezegun pytest

The problem

The following function greets the user according to the time of day.

greeting.py
from datetime import datetime


def greeting():
    hour = datetime.now().hour
    if hour < 12:
        return "Good morning"
    if hour < 18:
        return "Good afternoon"
    return "Good evening"


if __name__ == "__main__":
    print(datetime.now().strftime("%H:%M"), greeting())

The function reads the clock itself, so its result depends on when it runs. To test all three branches, a test would have to run in the morning, in the afternoon, and in the evening. The output below shows the time of the run.

$ python greeting.py
21:43 Good evening

Passing the time in

The simplest fix is a parameter. The function uses the current time only when the caller passes none.

greeter.py
from datetime import datetime


def greeting(now=None):
    if now is None:
        now = datetime.now()
    if now.hour < 12:
        return "Good morning"
    if now.hour < 18:
        return "Good afternoon"
    return "Good evening"

Production code calls greeting() as before, while tests pass fixed datetimes.

test_greeter.py
import unittest
from datetime import datetime

from greeter import greeting


class GreetingTest(unittest.TestCase):

    def test_morning(self):
        self.assertEqual(greeting(datetime(2026, 11, 19, 8, 0)), "Good morning")

    def test_noon(self):
        self.assertEqual(greeting(datetime(2026, 11, 19, 12, 0)), "Good afternoon")

    def test_evening(self):
        self.assertEqual(greeting(datetime(2026, 11, 19, 18, 0)), "Good evening")

    def test_default(self):
        self.assertIn(greeting(), {"Good morning", "Good afternoon", "Good evening"})


if __name__ == "__main__":
    unittest.main()

Each branch now has its own test, including the boundaries at 12:00 and 18:00. The last test calls the function without an argument; it can only check that the result is one of the valid greetings.

$ python -m unittest -v test_greeter.py
test_default (test_greeter.GreetingTest.test_default) ... ok
test_evening (test_greeter.GreetingTest.test_evening) ... ok
test_morning (test_greeter.GreetingTest.test_morning) ... ok
test_noon (test_greeter.GreetingTest.test_noon) ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

Injecting a clock

Code that reads the clock several times, such as an expiry check, takes a clock function instead of a value.

sessions.py
import time


class SessionStore:

    def __init__(self, ttl, clock=time.monotonic):
        self.ttl = ttl
        self.clock = clock
        self.sessions = {}

    def login(self, user):
        self.sessions[user] = self.clock()

    def is_active(self, user):
        started = self.sessions.get(user)
        return started is not None and self.clock() - started < self.ttl

The SessionStore class uses time.monotonic by default, which suits measuring durations because it never jumps when the system clock is changed. The clock parameter accepts any callable that returns seconds.

test_sessions.py
import unittest

from sessions import SessionStore


class FakeClock:

    def __init__(self, start=1000.0):
        self.now = start

    def __call__(self):
        return self.now

    def advance(self, seconds):
        self.now += seconds


class SessionTest(unittest.TestCase):

    def setUp(self):
        self.clock = FakeClock()
        self.store = SessionStore(ttl=1800, clock=self.clock)
        self.store.login("alice")

    def test_active_before_ttl(self):
        self.clock.advance(1799)
        self.assertTrue(self.store.is_active("alice"))

    def test_expired_after_ttl(self):
        self.clock.advance(1800)
        self.assertFalse(self.store.is_active("alice"))

    def test_unknown_user(self):
        self.assertFalse(self.store.is_active("bob"))


if __name__ == "__main__":
    unittest.main()

The FakeClock class is callable and returns a time that only changes when the test calls advance. The tests check the boundary of the 30-minute time-to-live without waiting: a session is active after 1799 seconds and expired after 1800.

$ python -m unittest -v test_sessions.py
test_active_before_ttl (test_sessions.SessionTest.test_active_before_ttl) ... ok
test_expired_after_ttl (test_sessions.SessionTest.test_expired_after_ttl) ... ok
test_unknown_user (test_sessions.SessionTest.test_unknown_user) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

Patching datetime

When code cannot be changed, unittest.mock.patch replaces an object while a test runs. The obvious target does not work for datetime.

patch_attempt.py
from datetime import datetime
from unittest import mock

import greeting

try:
    with mock.patch("datetime.datetime.now"):
        pass
except TypeError as e:
    print("TypeError:", e)

with mock.patch("greeting.datetime") as fake:
    fake.now.return_value = datetime(2026, 11, 19, 8, 0)
    print(greeting.greeting())
    print(fake.now.call_count)

print(greeting.datetime is datetime)

The datetime class is a built-in type written in C, and its attributes cannot be replaced, so patching datetime.datetime.now raises TypeError. The greeting module, however, has its own global name datetime, created by from datetime import datetime. Patching greeting.datetime replaces that name with a mock whose now returns 8:00. Patch where an object is looked up, not where it is defined. After the with block, the original class is back.

$ python patch_attempt.py
TypeError: cannot set 'now' attribute of immutable type 'datetime.datetime'
Good morning
1
True

Patching in tests

A plain mock replaces the whole class, so the code under test can no longer create datetimes. A mock that wraps the real class forwards all other calls to it.

test_greeting.py
import unittest
from datetime import datetime
from unittest import mock

import greeting


def at(hour, minute=0):
    fake = mock.Mock(wraps=datetime)
    fake.now.return_value = datetime(2026, 11, 19, hour, minute)
    return mock.patch("greeting.datetime", fake)


class GreetingTest(unittest.TestCase):

    def test_morning(self):
        with at(8):
            self.assertEqual(greeting.greeting(), "Good morning")

    @mock.patch("greeting.datetime", wraps=datetime)
    def test_evening(self, fake):
        fake.now.return_value = datetime(2026, 11, 19, 21, 15)
        self.assertEqual(greeting.greeting(), "Good evening")
        fake.now.assert_called_once_with()

    def test_wraps_keeps_constructor(self):
        with at(12):
            self.assertEqual(greeting.datetime(2027, 1, 1).year, 2027)
            self.assertEqual(greeting.greeting(), "Good afternoon")


if __name__ == "__main__":
    unittest.main()

The at helper builds a mock with wraps=datetime and fixes the return value of now. The second test uses patch as a decorator, which passes the mock to the test method, and verifies that now was called once. The third test shows that the constructor still works under the patch, because the wrapped class handles it.

$ python -m unittest -v test_greeting.py
test_evening (test_greeting.GreetingTest.test_evening) ... ok
test_morning (test_greeting.GreetingTest.test_morning) ... ok
test_wraps_keeps_constructor (test_greeting.GreetingTest.test_wraps_keeps_constructor) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

Patching sleep

Code that waits between retries makes tests slow. Patching sleep removes the waiting and lets us check the delays.

backoff.py
from time import sleep


def call_with_retry(func, attempts=4, delay=1.0):
    for attempt in range(1, attempts + 1):
        try:
            return func()
        except ConnectionError:
            if attempt == attempts:
                raise
            sleep(delay)
            delay *= 2

The call_with_retry function retries a call after a connection error and doubles the delay each time. It imports sleep directly from the time module.

test_backoff.py
import unittest
from unittest import mock

from backoff import call_with_retry


class RetryTest(unittest.TestCase):

    @mock.patch("backoff.sleep")
    def test_succeeds_on_third_call(self, fake_sleep):
        func = mock.Mock(side_effect=[ConnectionError, ConnectionError, "ok"])
        self.assertEqual(call_with_retry(func), "ok")
        self.assertEqual(fake_sleep.call_args_list,
                         [mock.call(1.0), mock.call(2.0)])

    @mock.patch("backoff.sleep")
    def test_gives_up(self, fake_sleep):
        func = mock.Mock(side_effect=ConnectionError("down"))
        with self.assertRaises(ConnectionError):
            call_with_retry(func, attempts=4)
        self.assertEqual([c.args[0] for c in fake_sleep.call_args_list],
                         [1.0, 2.0, 4.0])

    @mock.patch("time.sleep")
    def test_wrong_target(self, fake_sleep):
        func = mock.Mock(side_effect=[ConnectionError, "ok"])
        call_with_retry(func, delay=0.2)
        self.assertEqual(fake_sleep.call_count, 0)


if __name__ == "__main__":
    unittest.main()

The first two tests patch backoff.sleep and inspect the recorded calls: delays of one and two seconds before the third, successful attempt, and three delays before giving up. The third test patches time.sleep instead. That replaces the attribute of the time module, but backoff holds its own reference to the original function, so the mock is never called and the test really sleeps for 0.2 seconds, as the total run time shows.

$ python -m unittest -v test_backoff.py
test_gives_up (test_backoff.RetryTest.test_gives_up) ... ok
test_succeeds_on_third_call (test_backoff.RetryTest.test_succeeds_on_third_call) ... ok
test_wrong_target (test_backoff.RetryTest.test_wrong_target) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.201s

OK

Traveling with time-machine

The time-machine library changes the time for the whole process, so datetime.now, date.today, and time.time all return the new time, in every module, without patching names.

travel.py
import time
from datetime import UTC, date, datetime, timedelta

import time_machine

import greeting

eve = datetime(2026, 12, 24, 17, 0, tzinfo=UTC)

with time_machine.travel(eve, tick=False) as traveller:
    print(datetime.now(UTC), date.today(), time.time())
    print(datetime.now(), greeting.greeting())

    traveller.shift(timedelta(hours=8))
    print(datetime.now(UTC))

    traveller.move_to(datetime(2027, 1, 1, tzinfo=UTC))
    print(datetime.now(UTC))

with time_machine.travel(eve):
    first = time.time()
    time.sleep(0.1)
    print(round(time.time() - first, 1))

print(datetime.now(UTC).year)

The travel function works as a context manager or decorator. With tick=False, the clock stands still; the shift method moves it by a timedelta or seconds, and move_to jumps to another time. The destination is in UTC, and time-machine also sets the local time zone to UTC, so the naive datetime.now shows 17:00. By default the clock keeps ticking from the destination, as the measured 0.1 seconds show. After the block, the real time returns. The library does not change time.monotonic or time.perf_counter.

$ python travel.py
2026-12-24 17:00:00+00:00 2026-12-24 1798131600.0
2026-12-24 17:00:00 Good afternoon
2026-12-25 01:00:00+00:00
2027-01-01 00:00:00+00:00
0.1
2026

Naive destinations

A destination without a time zone is ambiguous, and time-machine treats the two naive forms differently.

naive_destinations.py
from datetime import datetime

import time_machine

with time_machine.travel(datetime(2026, 12, 24, 17, 0), tick=False):
    print(datetime.now())

with time_machine.travel("2026-12-24 17:00", tick=False):
    print(datetime.now())

time_machine.naive_mode = time_machine.NaiveMode.ERROR
try:
    with time_machine.travel(datetime(2026, 12, 24, 17, 0)):
        pass
except RuntimeError as e:
    print("RuntimeError:", e)

In the default mixed mode, a naive datetime is taken as UTC, so 17:00 becomes 18:00 local time in Bratislava, while a naive string is taken as local time. Setting naive_mode to ERROR makes naive destinations fail, which forces tests to state the time zone.

$ python naive_destinations.py
2026-12-24 18:00:00
2026-12-24 17:00:00
RuntimeError: Naive datetime provided while time_machine.naive_mode is set to ERROR. Please provide a timezone-aware datetime.

time-machine with pytest

Installing time-machine also registers a pytest plugin with the time_machine fixture and marker.

test_with_time_machine.py
from datetime import UTC, datetime, timedelta
from zoneinfo import ZoneInfo

import pytest

import greeting

local = ZoneInfo("Europe/Bratislava")


@pytest.mark.parametrize("hour, expected", [
    (8, "Good morning"),
    (12, "Good afternoon"),
    (18, "Good evening"),
])
def test_greeting(time_machine, hour, expected):
    time_machine.move_to(datetime(2026, 11, 19, hour, tzinfo=local))
    assert greeting.greeting() == expected


@pytest.mark.time_machine(datetime(2026, 11, 19, 11, 59, tzinfo=local), tick=False)
def test_shift(time_machine):
    assert greeting.greeting() == "Good morning"
    time_machine.shift(timedelta(minutes=1))
    assert greeting.greeting() == "Good afternoon"


def test_new_year(time_machine):
    time_machine.move_to(datetime(2026, 12, 31, 23, 59, 59, tzinfo=UTC), tick=False)
    time_machine.shift(1)
    assert datetime.now(UTC).year == 2027

The parametrized test moves the clock to three hours of a day in Bratislava. The marker sets the starting time for the second test, which then shifts the clock by a minute across noon. The fixture undoes the travel after each test.

$ pytest -v test_with_time_machine.py
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /home/user/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/user/python
plugins: time-machine-3.6.0
collecting ... collected 5 items

test_with_time_machine.py::test_greeting[8-Good morning] PASSED          [ 20%]
test_with_time_machine.py::test_greeting[12-Good afternoon] PASSED       [ 40%]
test_with_time_machine.py::test_greeting[18-Good evening] PASSED         [ 60%]
test_with_time_machine.py::test_shift PASSED                             [ 80%]
test_with_time_machine.py::test_new_year PASSED                          [100%]

============================== 5 passed in 0.02s ===============================

Testing time zones

When the destination has a ZoneInfo time zone, time-machine also switches the local time zone of the process. One instant can thus be tested in several zones.

zones.py
import time
from datetime import UTC, datetime
from zoneinfo import ZoneInfo

import time_machine

import greeting

instant = datetime(2026, 11, 19, 7, 30, tzinfo=UTC)

for key in ("Europe/Bratislava", "America/New_York", "Asia/Tokyo"):
    dest = instant.astimezone(ZoneInfo(key))
    with time_machine.travel(dest, tick=False):
        print(f"{key:18} {datetime.now():%H:%M} {time.strftime('%Z')}"
              f" {greeting.greeting()}")

print(datetime.now(UTC) > instant, time.strftime("%Z"))

At 7:30 UTC it is morning in Bratislava and New York, but afternoon in Tokyo. The naive datetime.now and time.strftime report the local time of the destination's zone. After the loop, the real time and the original CET zone are back.

$ python zones.py
Europe/Bratislava  08:30 CET Good morning
America/New_York   02:30 EST Good morning
Asia/Tokyo         16:30 JST Good afternoon
True CET

freezegun

The older freezegun library offers a similar API. Instead of changing the clock, it replaces the datetime classes with fake subclasses.

frozen.py
import time
from datetime import UTC, datetime

from freezegun import freeze_time

import greeting

with freeze_time("2026-12-24 17:00") as frozen:
    print(datetime.now(), datetime.now(UTC), greeting.greeting())
    print(time.time(), time.monotonic())

    frozen.tick(90)
    print(datetime.now())

    frozen.move_to("2027-01-01 08:00")
    print(datetime.now(), type(datetime.now()).__name__)

with freeze_time("2026-12-24 17:00", auto_tick_seconds=15):
    print([datetime.now().strftime("%M:%S") for _ in range(3)])


@freeze_time("2026-11-19 08:00")
def morning():
    return greeting.greeting()


print(morning())

The freeze_time function accepts a string, a datetime, or a date and works as a context manager or decorator. The frozen object has tick and move_to methods, and auto_tick_seconds advances the clock on every call. Note the differences from time-machine: the naive datetime.now returns the UTC time, 17:00, although the local zone is Bratislava; the monotonic clock is frozen too; and datetime.now returns a FakeDatetime. freezegun is pure Python and slower, because it scans loaded modules for references to replace; time-machine is a C extension that changes the clock functions directly.

$ python frozen.py
2026-12-24 17:00:00 2026-12-24 17:00:00+00:00 Good afternoon
1798131600.0 1798131600.0
2026-12-24 17:01:30
2027-01-01 08:00:00 FakeDatetime
['00:00', '00:15', '00:30']
Good morning

Source

unittest.mock – Where to patch

time-machine on GitHub

freezegun on GitHub

In this article we have made time-dependent code testable by passing the time and a clock into it, patched datetime and sleep with unittest.mock, and changed the clock with time-machine and freezegun. Passing the time in needs no library and keeps tests fast; the libraries help with code that we cannot change. See also Python unittest, Pytest tutorial, Python datetime, and Python zoneinfo.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.