How to filter a queryset for dates matching a given day?

10,187

Solution 1

today = datetime.datetime.today()
Example.objects.filter(
    date__year=today.year, 
    date__month=today.month, 
    date__day=today.day
)

Solution 2

Grab rows that have a create date greater than the current date using only the date() method of the datetime.now() class.

where row.createdate > datetime.datetime.now().date()

Solution 3

This should work.

import datetime
from django.db import models
from django.utils import timezone

class ExampleManager(models.Manager):
    def today(self):
        return super(ExampleManager, self).get_queryset().filter(pub_date__gte=datetime.datetime.today().date())

class ExampleModel(models.Model):
    # ...
    pub_date = models.DateTimeField(auto_now_add=True)
    objects = ExampleManager()
Share:
10,187
Kookoriko
Author by

Kookoriko

Student of Informatics. Interested on Video Game Design and Programming, AI, Java, new technologies and foreign languages.

Updated on July 24, 2022

Comments

  • Kookoriko
    Kookoriko almost 2 years

    I am trying to build a query for a view in Django in which I want to retrieve rows with today date (no matter the time).

    I was thinking in a range between current date and datetime.datetime.now()

    However I can't get only the date but not the time.

    I have this:

    now = datetime.datetime.now()
    today = datetime.datetime.today()
    var = Example.objects.filter(date__gt=datetime.date(today.year(), today.month(), today.day()), fecha__lt=now)