Skip to content

Instantly share code, notes, and snippets.

@diptangsu
Forked from cansadadeserfeliz/views.py
Last active January 18, 2024 16:52
Show Gist options
  • Save diptangsu/7c679e1785e2d5d8203693a7d64a47c9 to your computer and use it in GitHub Desktop.
Save diptangsu/7c679e1785e2d5d8203693a7d64a47c9 to your computer and use it in GitHub Desktop.
Django: filter DatetimeField by today (max and min time)
# source: http://stackoverflow.com/questions/1317714/how-can-i-filter-a-date-of-a-datetimefield-in-django
from django.utils import timezone
today_min = datetime.combine(timezone.now().date(), datetime.today().time().min)
today_max = datetime.combine(timezone.now().date(), datetime.today().time().max)
objetcs_for_today = MyModel.objects.filter(date__range=(today_min, today_max))
@gulsoy83
Copy link

this one worked for me:

now = datetime.now()
today_min = datetime.combine(now,  time.min)
today_max = datetime.combine(now, time.max)
objects = MyModel.objects.filter( Q(date__gte = today_min) & Q(date__lte = today_max) )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment