Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 897143
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T14:50:22+00:00 2026-05-15T14:50:22+00:00

Suppose I have the following Event model: from django.db import models import datetime class

  • 0

Suppose I have the following Event model:

from django.db import models
import datetime

class Event(models.Model):
    date_start = models.DateField()
    date_end = models.DateField()

    def is_over(self):
        return datetime.date.today() > self.date_end

I want to test Event.is_over() by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we’ve reached that future date.

I’d like to be able to stub ALL system time objects as far as python is concerned. This includes datetime.date.today(), datetime.datetime.now(), and any other standard date/time objects.

What’s the standard way to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T14:50:23+00:00Added an answer on May 15, 2026 at 2:50 pm

    EDIT: Since my answer is the accepted answer here I’m updating it to let everyone know a better way has been created in the meantime, the freezegun library: https://pypi.python.org/pypi/freezegun. I use this in all my projects when I want to influence time in tests. Have a look at it.

    Original answer:

    Replacing internal stuff like this is always dangerous because it can have nasty side effects. So what you indeed want, is to have the monkey patching be as local as possible.

    We use Michael Foord’s excellent mock library: http://www.voidspace.org.uk/python/mock/ that has a @patch decorator which patches certain functionality, but the monkey patch only lives in the scope of the testing function, and everything is automatically restored after the function runs out of its scope.

    The only problem is that the internal datetime module is implemented in C, so by default you won’t be able to monkey patch it. We fixed this by making our own simple implementation which can be mocked.

    The total solution is something like this (the example is a validator function used within a Django project to validate that a date is in the future). Mind you I took this from a project but took out the non-important stuff, so things may not actually work when copy-pasting this, but you get the idea, I hope 🙂

    First we define our own very simple implementation of datetime.date.today in a file called utils/date.py:

    import datetime
    
    def today():
        return datetime.date.today()
    

    Then we create the unittest for this validator in tests.py:

    import datetime
    import mock
    from unittest2 import TestCase
    
    from django.core.exceptions import ValidationError
    
    from .. import validators
    
    class ValidationTests(TestCase):
        @mock.patch('utils.date.today')
        def test_validate_future_date(self, today_mock):
            # Pin python's today to returning the same date
            # always so we can actually keep on unit testing in the future :)
            today_mock.return_value = datetime.date(2010, 1, 1)
    
            # A future date should work
            validators.validate_future_date(datetime.date(2010, 1, 2))
    
            # The mocked today's date should fail
            with self.assertRaises(ValidationError) as e:
                validators.validate_future_date(datetime.date(2010, 1, 1))
            self.assertEquals([u'Date should be in the future.'], e.exception.messages)
    
            # Date in the past should also fail
            with self.assertRaises(ValidationError) as e:
                validators.validate_future_date(datetime.date(2009, 12, 31))
            self.assertEquals([u'Date should be in the future.'], e.exception.messages)
    

    The final implementation looks like this:

    from django.utils.translation import ugettext_lazy as _
    from django.core.exceptions import ValidationError
    
    from utils import date
    
    def validate_future_date(value):
        if value <= date.today():
            raise ValidationError(_('Date should be in the future.'))
    

    Hope this helps

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.