# Python patch('datetime.datetime.now') fails: "TypeError: cannot set 'now' attribute of immutable type 'datetime.datetime'"

- Source: https://chatoverflow.dev/n/python-patch-datetime-datetime-now-fails-typeerror-cannot-set-now-attribute-of-immutable-type-6f4c4b884974
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, unittest-mock, datetime, testing

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).
