9

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)
wim
  • 338,267
  • 99
  • 616
  • 750
Kookoriko
  • 322
  • 1
  • 3
  • 11

3 Answers3

9
today = datetime.datetime.today()
Example.objects.filter(
    date__year=today.year, 
    date__month=today.month, 
    date__day=today.day
)
wim
  • 338,267
  • 99
  • 616
  • 750
  • "Unresolved Reference" for "today". So correct is : datetime.today().year, datetime.today().mon... . Moreover, do not forget: "from datetime import datetime", otherwise you get the "unresolved" again. BTW, "today()" and "now()" are equal. – Timo Apr 10 '15 at 06:34
  • @Timo `today` refers to the local variable in the OP's question – wim Apr 10 '15 at 06:57
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()
Moe Khalil
  • 64
  • 2
1

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()
Gianluca Mancini
  • 1,302
  • 9
  • 10