Skip to content

Instantly share code, notes, and snippets.

@iwstkhr
Created March 17, 2024 19:57
Show Gist options
  • Save iwstkhr/1e22495dd0457da1251c53bee695624d to your computer and use it in GitHub Desktop.
Save iwstkhr/1e22495dd0457da1251c53bee695624d to your computer and use it in GitHub Desktop.
Mocking datetime in Python
from datetime import datetime
from pytest_mock import MockerFixture
def test_your_function(mocker: MockerFixture):
now = datetime.strptime('2024-01-02 12:34:56', '%Y-%m-%d %H:%M:%S')
mock = mocker.MagicMock(wraps=datetime)
mock.now.return_value = now
mocker.patch('src.your_module.datetime', new=mock)
# Write your testing code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment