Mocking Django Timezone

I use in a lot of my code. It returns the datetime in the timezone specified in One side effect of using this function is that during testing, you may want “now()” to be a fixed date time. No worries. Mock to the rescue. Here is the code:

import datetime

from django.test import TestCase
from django.utils import timezone

import mock

# Make now() a constant
NOW_FOR_TESTING = datetime.datetime(2015, 10, 10, 10)

# This is the function that replaces
def mocked_now():
    return NOW_FOR_TESTING

# This function shows that the mocking is in effect even outside of the TestMyTest scope.
def a_func():

@mock.patch('', side_effect=mocked_now)
class TestMyTest(TestCase):
    def test_time_zone(self, *args):
        # After patching, mock passes in some extra vars. Put *args to handle them.
        self.assertEqual(, NOW_FOR_TESTING)
        self.assertEqual(mocked_now(), NOW_FOR_TESTING)

Note that you need to add the “*args” argument to the methods in your TestCase class.



Here is how to add to the default DATETIME_INPUT_FORMATS in Django

from django.conf.global_settings import DATETIME_INPUT_FORMATS

DATETIME_INPUT_FORMATS += ('%Y-%m-%d %I:%M %p', )

Django Datetime Widget

Usually I use datetimes as timestamps that are automatically set. Thus I do not need a datetime widget. But in my current project I needed a datetime widget that was user friendly. There are a few options. Which one was best?

The answer depends on what dependencies your project already has. For example, django-bootstrap3-datetimepicker seems pretty awesome. But I had trouble getting it to work with my project. I suspect part of the problem is I am using django-crispy (I am not sure this is the problem). Anyway, I am pretty comfortable with javascript, so I thought I would just download the javascript this app uses and wire it up my self with javascript. Then I found that I needed to download even more dependencies. So I decide to look around for something else.

That’s when I rediscovered a module by Trent Richardson (jquery-ui-timepicker-addon). I have used some of his modules in the past and had good luck. I am already using jquery. This module will not interfere with django-crispy. Turns out it worked great!