Django query datetime for objects older than 5 hours

user523513 picture user523513 · Apr 27, 2012 · Viewed 57.3k times · Source

I'm trying to write a Django query for widgets that are more than 5 hours old and I'm a bit lost. The widget model has a DateTimeField that is populated with the creation time of the widget.

Answer

David Robinson picture David Robinson · Apr 27, 2012

If Widget is the name of your model, and it has a DateTimeField attribute named created, the query would be:

from datetime import datetime, timedelta

time_threshold = datetime.now() - timedelta(hours=5)
results = Widget.objects.filter(created__lt=time_threshold)

Note that created__lt means "created is less than".