How can I test a function that depends on the current time?
Quick answer
Pass the time into the calculation instead of having the calculation fetch it internally. Your application can obtain the current time with datetime.now(), while tests supply a fixed datetime value. That makes the result repeatable and lets you check exact boundary cases without relying on when the test happens to run. If you use a clock function, keep the same idea: substitute a predictable clock in the test.
The question, the details, the next step.
A practical checklist
Identify the time-based rule and make the time an explicit input.
Keep reading the real clock outside the calculation being tested.
Use fixed test times rather than calling
datetime.now()in the test.Test before, at, and after the boundary, matching the intended rule.
Decide explicitly how your application represents time and handles invalid inputs.
A few more useful answers
Should I patch `datetime.now()` in every test?
Not for a calculation that can accept a time value directly: pass a fixed value to it. Patching or injecting a clock can be useful when testing code whose responsibility includes obtaining the time.
Why test the exact deadline, not just before and after?
The equality case reveals whether your rule treats the deadline itself as expired. Make that behavior explicit in both the comparison and the test.
Does this example settle which timezone my code should use?
No. It shows how to control the time input in a test, not which timezone or time representation fits your application.
Sources
References used for this guide.
- [S1] Python 3.14 datetime — Basic date and time types docs.python.org · Checked
