title: Django Test Mock Datetime Now
body: <p>I have a Django test where I need to mock datetime.now(), because the view that it tests uses datetime.now()</p>
  
  <p>I'm using Michael Foord's mock library, version 1.0.1.<br>
  I'm looking for a solution without using other libraries such as freezegun.</p>
  
  <p>Most examples like <a href="https://stackoverflow.com/a/4482067/7603394">this</a> and <a href="http://blog.xelnor.net/python-mocking-datetime/" rel="nofollow noreferrer">this</a> import datetime and override it, but I'm importing datetime.datetime and im trying to override it, and for some reason this doesn't work.</p>
  
  <p>Overriding datetime works:</p>
  
  <pre><code>import mock
  import datetime
  
  class FixedDate(datetime.datetime):
  
      @classmethod
      def now(cls):
          return cls(2010, 1, 1)
  
  @mock.patch('datetime.datetime', FixedDate)
  def myTest():
      print(datetime.datetime.now())
  
  myTest()
  </code></pre>
  
  <p>But I want to import datetime.datetime and do something like this:</p>
  
  <pre><code>import mock
  from datetime import datetime
  
  class FixedDate(datetime):
  
      @classmethod
      def now(cls):
          return cls(2010, 1, 1)
  
  @mock.patch('datetime', FixedDate)
  def myTest():
      print(datetime.now())
  
  myTest()
  </code></pre>
  
  <p>This causes the TypeError: Need a valid target to patch. You supplied: 'datetime'.</p>
  
  <p>The Mock library also states:</p>
  
  <blockquote>
    <p>target should be a string in the form ‘package.module.ClassName’. The target is imported and the specified object replaced with the new object, so the target must be importable from the environment you are  calling patch from.</p>
  </blockquote>
  
  <p>Is there any way to path only the datetime and not the datetime.datetime?</p>
  
  <p>Nb. I saw also <a href="https://stackoverflow.com/questions/13073281/how-to-mock-pythons-datetime-now-in-a-class-method-for-unit-testing">this</a> example, but it won't work for me, cause I dont have one function that returns the datetime, but my view uses datetime.now()</p>