Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

T is for time-machine - Python A to Z

Code in this blog post was written with versions: Python: 3.14

Python A-Z is a blog series about Python. Each day, I share insights, ideas and examples for different parts of Python development that match with the letter of the day. Blaugust is an annual blogging festival in August where the goal is to write a blog post every day of the month.

Quite a lot of our software has code in it that deals with time: either by displaying some time (current time, creation/modification time, countdowns etc.) or by doing different logic based on the current time (”show this for the week leading into Christmas” type of deal).

Time is wibbly wobbly — as my favourite Doctor would say — and when writing tests, it means that we need tools to control time. If we let tests run against the system clock, they will fail sometimes and succeed other times. That doesn’t make them very good tests.

Adam Johnson’s time-machine is a lovely library with a great logo to do exactly that (and fast as well).

The interface is nice and simple. A decorator lets you travel to a specific time per function/test:

import datetime
import time_machine

# The first argument is the time to travel to
# tick defines if time should continue moving (True)
# or be frozen (False)
@time_machine.travel('2020-03-10', tick=False)
def test_a_good_day():
	assert datetime.date.today().isoformat() == '2020-03-10'


If something above resonated with you, let's start a discussion about it! Email me at juhis@hamatti.org and share your thoughts. This year, I want to have more deeper discussions with people from around the world and I'd love if you'd be part of that.