Shankz
Shankz

Reputation: 33

How to fetch the data for the current hour in Django

I am trying to fetch data from a Django model while filtering its DateTimeField() to the current date and current hour.

models.py

class Log(models.Model):
    DATE                    =   models.DateTimeField()
    TYPE                    =   models.CharField(max_length=32,primary_key=True)
    class Meta:
        db_table='LOG'
        indexes=[
                models.Index(fields=['DATE','TYPE'])
                ]

views.py

obj=Log.objects.filter()

How can I define my filter in such a way that it returns the data of current hour only?

Upvotes: 0

Views: 381

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47374

If you want to filter by the current hour and by current date you can use __date and __hour filters:

import datetime
now = datetime.datetime.now()
obj=Log.objects.filter(DATE__date=now.date(), DATE__hour=now.hour)

Upvotes: 2

Related Questions