Home > Enterprise >  how to filter posts for a specific hour from its publishing time
how to filter posts for a specific hour from its publishing time

Time:10-15

I'm trying to show my posts for a specific time here is my models.py

class Booking(models.Model):
    check_in = models.DateTimeField(default=timezone.now)
    check_out = models.DateTimeField(blank=True,null=True)

i want display object for 12 hours after check out for example if we have an object its check out is 14/10/2021 10AM then show that post till 10PM !

i tried it , but didnt work Booking.objects.filter(check_out__hour=12)

is it possible please ? thank you in advance

CodePudding user response:

You can filter with:

from datetime import timedelta
from django.db.models.functions import Now

Booking.objects.filter(
    check_out__gte=Now()-timedelta(hours=12)
)

you can filter further such that no objects with a check_out that is later than now are filtered out with a __range lookup [Django-doc]:

from datetime import timedelta
from django.db.models.functions import Now

Booking.objects.filter(
    check_out__range=(Now()-timedelta(hours=12), Now())
)

Here Now() is the timestamp of the database.

We can also work with the timestamp of the webserver machine with:

from datetime import timedelta
from django.utils.timezone import now

Booking.objects.filter(
    check_out__range=(now()-timedelta(hours=12), now())
)
  • Related