Find Out A Datetime is Between Two Datetimes in Django

Question:

I’m making a blog-like platform which includes an event page. I have a model as below:

class Event(models.Model):
    dtime_start = models.DateTimeField(null=False, blank=False)
    dtime_end = models.DateTimeField(null=False, blank=False)

Assuming I have a view called event_main which projects all events. However, I want to project currently active events at the top of page, highlighted. So what I need is:

  1. to get exact request datetime of client
  2. to filter Event instances having the request datetime between dtime_start and dtime_end

I thought of solutions including for loops and put the results in the list, however I don’t really want to put model instances to a list, since there are QuerySets. Is there a built-in way to do this in Django?

###############
# Environment #
###############
python 3.2.5
pypy 2.4.0
django 1.8.7
Asked By: Eray Erdin

||

Answers:

The dtime_start <= input AND dtime_end >= output:

Event.objects.filter(dtime_start__lte=datetime.date(y, m, d), dtime_start__gte=datetime.date(y, m, d))

For more information, refer to the documentation.

Answered By: nlgn

To get the request datetime of the client, you may :

  1. Rely on the "Date" header (request.META.get('HTTP_DATE')),
  2. Rely on the current date of the server and the client timezone
  3. Fallback to the current date of the server

Then you can filter with common lookups as you would to for an integer:

Event.objects.filter(dtime_start__lte=request_datetime,
                     dtime_end__gte=request_datetime)

Note: Unless you have some specific reasons to rely on the client’s date, you should probably avoid it and simply use datetime.now() or timezone.now() (both would work the same, as Django handles timezone conversion when dealing with the database). If you rely on the client’s date, beware that they could temper with the Date header to access past or future events.

Answered By: Antoine Pinsard
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.