且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Django中比较日期和日期时间

更新时间:2022-04-22 22:32:13

也许有一个更合适的解决方案,但是快速检查表明这可以解决问题: / p>

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.

重要的是,您要存储一个精确的时间,直到毫秒,您正在将其与仅能精确到一天的东西进行比较。 django / python不会将小时,分钟和秒扔掉,而是将它们默认为0。因此,如果您的记录创建于2011-4-6T06:34:14am,那么它将比较2011-4-6T:06:34:14am到2011-4-6T00:00:00,而不是2011-4-6(从创建日期开始)到2011-4-6(从timezone.now()。date()开始)。有帮助吗?

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?