Compare date and datetime in Django

社会主义新天地 提交于 2020-06-24 22:23:46

问题


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?


回答1:


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?




回答2:


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




回答3:


Try this

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


来源:https://stackoverflow.com/questions/10048216/compare-date-and-datetime-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!