Python django 在日期范围内按日期时间过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20379246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:18:01  来源:igfitidea点击:

django filter by datetime on a range of dates

pythondjangodatetime

提问by user2139745

I have a model with field "created_at", and I have a list of dates. So, I want to get all the models that are created in the date range. How ?

我有一个带有“created_at”字段的模型,我有一个日期列表。所以,我想获取在日期范围内创建的所有模型。如何 ?

I know that we can compare datetime and date easily using:

我知道我们可以使用以下方法轻松比较日期时间和日期:

queryset.filter(created_at__startswith=date)

But, I have a range of dates, so how ?
Let me know for more information.

但是,我有一个日期范围,那么如何呢?
让我知道更多信息。

回答by Simeon Visser

You can use __gte(greater than or equal) and __lte(less than or equal). For example:

您可以使用__gte(大于或等于)和__lte(小于或等于)。例如:

queryset.filter(created_at__gte=datetime.date.today())

回答by JamesO

You can use rangee.g.

您可以使用范围例如

first_date = datetime.date(2005, 1, 1)
last_date = datetime.date(2005, 3, 31)
queryset.filter(created_at__range=(first_date, last_date))

回答by Aamir Adnan

You can use rangelookup. Just find the lowest and greater date and then apply it as:

您可以使用范围查找。只需找到最低和更大的日期,然后将其应用为:

queryset.filter(created_at__range=(start_date, end_date))

回答by user956424

回答by Ali Shamakhi

You can combine dateand rangefield lookups:

您可以结合日期范围字段查找:

queryset.filter(created_at__date__range=(start_date, end_date))