Using datetime.now() in Django view
<p><strong>The Code</strong></p>

<p>I am using datetime.now() as part of a filter in a Django view as follows:</p>

<pre><code>def get_now():
    return timezone.now()

class BulletinListView(ListView):
    model = Announcement
    template_name = 'newswire/home.html'

    def get_context_data(self, **kwargs):
        context = super(BulletinListView, self).get_context_data(**kwargs)

        try:
            published_announcements = Announcement.objects.filter(publish_start_date__lte=get_now(), publish_end_date__gte=get_now()).filter(hidden=False, under_review=False).extra(order_by=['-publish_start_date', 'publish_end_date'])
        except Announcement.DoesNotExist:
            published_announcements = None

        if published_announcements is not None:
            context['announcements'] = published_announcements
            max_print_annoucements = int(config.MAX_PRINT_ANNOUCEMENTS)
            context['announcements_print'] = published_announcements[
                :max_print_annoucements]
            context['more_annoucements_online_count'] = published_announcements.count() - max_print_annoucements

        return context
</code></pre>

<p><strong>Edit:</strong> Managed to update and include more code</p>

<p>It works correctly and gets announcements that are supposed to be published and are not hidden or under review according to to the date supplied by <code>datetime.now()</code></p>

<p><strong>The Problem</strong></p>

<p>I use <code>datetime.datetime.now()</code> to filter out old announcements but I realised after a day in the production environment that <code>datetime.datetime.now()</code> is being evaluated only when the server starts and the value does not update each time the view is called which results in the wrong data being filtered when the next day comes around. This is also affecting another function which retrieves upcoming birthdays in the next 7 days.</p>

<p><strong>Things I Read and Tried</strong></p>

<p>I have seen a number of questions about using the callable <code>datetime.now</code> instead of <code>datetime.now()</code> but only in the context of setting default values in the model.</p>

<p>I have defined a function as follows thinking it would force <code>datetime.now</code> to be evaluated again but it does not seem to work. </p>

<pre><code>def get_now():
    return timezone.now())
</code></pre>

<p>When I pass the date i get to the context to see what I'm getting, I see that the date and time doesn't advance past the time I deploy the server.</p>

<p>I have seen a number of examples of using datetime.now() in the view but none run into this issue.</p>

<p>I suspect I have never seen this in development because I run the development gunicorn server with the --reload option and <code>datetime.now()</code> is constantly evaluated when I save changes and the server restarts.</p>

<p><a href="http://stackoverflow.com/questions/10741201/django-seems-to-be-caching-datetime-now">This problem</a> seems to be similar but I'm not sure how it is similar/different to my situation</p>

<p><strong>Context:</strong></p>

<p>I am writing a Django application and my development and production environments are implemented using docker and the application run behind an nginx proxy</p>

<pre><code>/usr/local/bin/gunicorn app.wsgi:application -w 2 -b :8000
</code></pre>

<blockquote>
  <p>the value does not update each time the view is called which results
  in the wrong data being filtered when the next day comes around</p>
</blockquote>

<p>You have to decide which "next day" are you talking about? Is it:</p>

<ol>
<li>The next day for the user visiting your site.</li>
<li>The next day for you, visiting the site.</li>
<li>The next day for the timezone that is set on the server.</li>
</ol>

<p>Each one of these will end up in a "wrong" result, when in fact nothing is actually wrong with the code.</p>

<p>This is because your code is naive when it comes to timezones. It basically ignores timezones completely.</p>

<p>This is a complicated topic, and django has a <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/" rel="nofollow">complete section of the manual</a> dedicated to dealing with timezones. I suggest reading it once or twice as there are many ways timezones can affect your site.</p>

<p>Finally, you can clean up your code a bit, like this:</p>

<pre><code>try:
   max_print_annoucements = int(config.MAX_PRINT_ANNOUCEMENTS)
except ValueError:
   max_print_announcements = 0

published_announcements = Announcement.objects.filter(publish_start_date__lte=get_now(),
                                                      publish_end_date__gte=get_now())
                                              .filter(hidden=False, under_review=False)
                                              .extra(order_by=['-publish_start_date',
                                                               'publish_end_date'])

context['announcements'] = published_announcements
context['announcements_print'] = published_announcements[:max_print_annoucements]
context['more_annoucements_online_count'] = abs(published_announcements.count() - max_print_annoucements)
</code></pre>

python django datetime gunicorn