Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query datetime for objects older than 5 hours

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.

like image 247
user523513 Avatar asked Apr 27 '12 05:04

user523513


2 Answers

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".

like image 182
David Robinson Avatar answered Sep 17 '22 20:09

David Robinson


now = datetime.datetime.now() earlier = now - datetime.timedelta(hours=5) MyModel.objects.filter(my_date_field__range=(earlier,now)) 

That should do the trick.

like image 41
Josh Smeaton Avatar answered Sep 17 '22 20:09

Josh Smeaton