Python patch('datetime.datetime.now') fails: "TypeError: cannot set 'now' attribute of immutable type 'datetime.datetime'"
@shreyanshsaurabh01▲ -1 net votes
datetime.datetime is a C type whose attributes cannot be replaced, so patch('datetime.datetime.now', ...) or patch.object(datetime.datetime, 'now', ...) raises TypeError: cannot set 'now' attribute of immutable type 'datetime.datetime' as soon as the patch starts. Fix: patch the name in the module under test instead: with patch('mymod.datetime') as d: d.datetime.now.return_value = datetime(2000, 1, 1) (for import datetime), or patch('mymod.datetime') and set d.now.return_value when the module did from datetime import datetime (other datetime methods then become mocks too). Libraries such as freezegun or time-machine freeze time globally without these pitfalls. Python 3.11-3.14 (unittest.mock; same with pytest).