Skip to content
Advertisement

How to monkeypatch builtin function datetime.datetime.now?

I’d like to make sure that datetime.datetime.now() returns a specific datetime for testing purposes, How do I do this? I’ve tried with pytest’s monkeypatch

monkeypatch.setattr(datetime.datetime,"now", nowfunc)

But this gives me the error TypeError: can't set attributes of built-in/extension type 'datetime.datetime'

Advertisement

Answer

As the error tells you, you can’t monkeypatch the attributes of many extension types implemented in C. (Other Python implementations may have different rules than CPython, but they often have similar restrictions.)

The way around this is to create a subclass, and monkeypatch the class.

For example (untested, because I don’t have pytest handy… but it works with manual monkeypatching):

class patched_datetime(datetime.datetime): pass
monkeypatch.setattr(patched_datetime, "now", nowfunc)
datetime.datetime = patched_datetime
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement