'How to filter objects in Django by time since last 24 hours?
Assuming there's a starting time from 00:00 to 00:00 every day, how best are Django objects filtered by time, based on the current day? I initially came up with this:
from django.utils import timezone
yesterday = timezone.now() - timezone.timedelta(1)
qs = Foo.objects.filter(date__gte=yesterday)
##
yesterday = datetime.date.today() - datetime.timedelta(1)
qs = Foo.objects.filter(date__gte=yesterday)
However, this is not particularly right. I would prefer time starting exactly from 00:00 to timezone.now() -so something like Foo.objects.filter(date__range=[00:00, timezone.now()]) Thank you.
Solution 1:[1]
Yevgeniy Kosmak's answer is correct, use datetime_field__date= filter.
Here are the Django docs
Also you can use date/datetime - timedelta() pattern with others arguments in timedelta, like
timedelta(
days=50,
seconds=27,
microseconds=10,
milliseconds=29000,
minutes=5,
hours=8,
weeks=2
)
docs are here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | fanni |
