Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare date and datetime in Django

I have a model with a datetime field:

class MyModel(models.Model):
    created = models.DateTimeField(auto_now = True)

I want to get all the records created today.

I tried:

MyModel.objects.all().filter(created = timezone.now())

and

MyModel.objects.all().filter(created = timezone.now().date())

But always got an empty set. What is the correct way in Django to do this?

EDIT:

It looks strange, but a record, created today (06.04.2012 23:09:44) has date (2012-04-07 04:09:44) in the database. When I'm trying to edit it in the admin panel it looks correct (06.04.2012 23:09:44). Does Django handle it somehow?

like image 763
Just_Mad Avatar asked Apr 06 '12 19:04

Just_Mad


2 Answers

Since somewhere in 2015:

YourModel.objects.filter(some_datetime__date=some_date)

i.e. __date after the datetime field.

https://code.djangoproject.com/ticket/9596

like image 52
MZA Avatar answered Nov 10 '22 01:11

MZA


There may be a more proper solution, but a quick workup suggests that this would work:

from datetime import timedelta

start_date = timezone.now().date()
end_date = start_date + timedelta( days=1 ) 
Entry.objects.filter(created__range=(start_date, end_date))

I'm assuming timezone is a datetime-like object.

The important thing is that you're storing an exact time, down to the millisecond, and you're comparing it to something that only has accuracy to the day. Rather than toss the hours, minutes, and seconds, django/python defaults them to 0. So if your record is createed at 2011-4-6T06:34:14am, then it compares 2011-4-6T:06:34:14am to 2011-4-6T00:00:00, not 2011-4-6 (from created date) to 2011-4-6 ( from timezone.now().date() ). Helpful?

like image 14
mklauber Avatar answered Nov 10 '22 01:11

mklauber