简体   繁体   中英

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?

Since somewhere in 2015:

YourModel.objects.filter(some_datetime__date=some_date)

ie __date after the datetime field.

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

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?

Try this

from datetime import datetime
now=datetime.now()
YourModel.objects.filter(datetime_published=datetime(now.year, now.month, now.day))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM