[Django]-Looking up relative dates from Django DateTimeField

5👍

Pass datetime.datetime object (substracted by datetime.timedelta object):

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 12, 29, 21, 54, 30, 836000)
>>> now - datetime.timedelta(days=1)
datetime.datetime(2013, 12, 28, 21, 54, 30, 836000)

import datetime

cars = MyClass.objects.filter(date__lt=datetime.datetime.now() - datetime.timedelta(days=1))

UPDATE Comment by Mikko Ohtamaa:

Also to avoid problems with timezones I recommend using timezone.now() instead of datetime.datetime.now() (available since Django 1.4)

import datetime
from django.utils import timezone

cars = MyClass.objects.filter(date__lt=timezone.now() - datetime.timedelta(days=1))

Leave a comment