title: Why python's monkeypatch doesn't work when importing a class instead of a module?
body: <p>I was having issues while using the code of the accepted answer <a href="https://stackoverflow.com/questions/20503373/how-to-monkeypatch-pythons-datetime-datetime-now-with-py-test">here</a>.</p>
  
  <p><em>The code works depending on how I do the import of datetime.</em> Why is that? Is it possible to mock it so it works both ways?</p>
  
  <p>I am using <code>Python 3.4</code>. The following code illustrates the problem:</p>
  
  <pre><code>import pytest
  from datetime import datetime
  
  mockdate = datetime(2000, 1, 1, 0, 0, 0)
  
  @pytest.fixture(autouse=True)
  def patch_datetime_now(monkeypatch):
      class mydatetime:
          @classmethod
          def now(cls):
              return mockdate
  
      monkeypatch.setattr('datetime.datetime', mydatetime)
  
  def test_doesnt_work():
      assert datetime.now() == mockdate
  
  def test_works():
      import datetime
      assert datetime.datetime.now() == mockdate
  </code></pre>