Mocking datetime in Python


It might be that pythonistas really don’t like monkey patching, but as I couldn’t find a quick answer on how to mock time in Python I thought I write down here how I did it.

It’s no big deal really, just replace datetime in the module tested with a local implementation. In my case I wanted to to mock datetime.utcnow and to match the call I created a class with utcnow as a static method.

class TimeStandsStill:
  # define the methods you want mocked
  # Here we have
  def utcnow():
    return datetime(2015, 8, 1)

def test_setup_result_without_error():
  my_module.datetime = TimeStandsStill

Really, not a big deal.