Search code examples
pythondatetimemockingpytest

How to monkeypatch python's datetime.datetime.now with py.test?


I need to test functions which uses datetime.datetime.now(). What is the easiest way to do this?


Solution

  • You need to monkeypatch datetime.now function. In example below, I'm creating fixture which I can re-use later in other tests:

    import datetime
    import pytest
    
    FAKE_TIME = datetime.datetime(2020, 12, 25, 17, 5, 55)
    
    @pytest.fixture
    def patch_datetime_now(monkeypatch):
    
        class mydatetime(datetime.datetime):
            @classmethod
            def now(cls):
                return FAKE_TIME
    
        monkeypatch.setattr(datetime, 'datetime', mydatetime)
    
    
    def test_patch_datetime(patch_datetime_now):
        assert datetime.datetime.now() == FAKE_TIME