Testing time-dependent logic and DST changes with time_machine

Backend Live Coding November 13, 2026 python

Never a bare datetime.now() inside the logic: either I pass the time in as a parameter, or I "freeze" time in the test.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# ======================================================================
# Q: How do you test logic that depends on the current time?
#
# Never a bare datetime.now() inside the logic: either I pass the time in as a
# parameter, or I "freeze" time in the test.
# ======================================================================

import time_machine

@time_machine.travel(datetime(2026, 10, 25, 1, 30, tzinfo=UTC))   # DST change in Europe
def test_slot_active_after_dst_change():
    screen = Screen(timezone='Europe/Athens')
    slot = Slot(weekdays=[6], start_time=time(4, 0), end_time=time(5, 0))
    assert is_slot_active(slot, screen, datetime.now(UTC))