Interview Prep/Python for DevOps/Testing, services & metrics

How do you test code that depends on the current time?

AdvancedConceptTesting, services & metrics
Answer

Do not call datetime.now() deep inside logic. Either inject now as a parameter (simplest, clearest), or freeze time in tests with freezegun or time-machine:

import time_machine
@time_machine.travel("2026-11-09 00:00:00+00:00")
def test_expiry():
    assert is_expired({"StartTime": datetime(2026, 7, 1, tzinfo=UTC)}, days=90)

Time-based retention rules (snapshot cleanup, certificate expiry, key rotation) are exactly where an off-by-one deletes something it should not.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics