Django过滤器基于日期的日期仅限于日期 [英] Django filter datetime base on date only

查看:192
本文介绍了Django过滤器基于日期的日期仅限于日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在筛选BaseDatatableView中由用户以下列格式输入的日期中设置的查询:mm / dd / yyyy。所以start_date是这种格式,并将转换为一个datetime与strptime,见下面。

I'm trying to filter the query set in the BaseDatatableView on a date that's entered in by the user in the following format: mm/dd/yyyy. So start_date is in that format and will get converted to a datetime with strptime, see below.

我想要比较它完全一个日期datetimefield在db,但我想要匹配的月,日,年完全,无视时间。这是我所拥有的,所以不工作。

I'd like to compare it to exactly a date datetimefield in the db, but i'd like to match the month, day, year exactly, disregarding the time. This is what I have so that doesn't work.

class AppointmentListJson(LoginRequiredMixin, BaseDatatableView):
             ....
    start_date = params.get('start_date', '')
    if start_date:  
        qs = qs.filter(start_date__contains=datetime.strptime(
            start_date, DATE_FORMAT))

    return qs

感谢

推荐答案

一个选项(在过滤器中突破日期):

One option (break the date down in the filter):

start_date = datetime.strptime(start_date, DATE_FORMAT)
qs = qs.filter(
    start_date__year=start_date.year,
    start_date__month=start_date.month,
    start_date__day=start_date.day
)

另一个选项(设置日期和使用范围的最小/ ):

Another option (set the min/max time for the date and use range):

from datetime import datetime
start_date = datetime.strptime(start_date, DATE_FORMAT)
start_date_range = (
    # The start_date with the minimum possible time
    datetime.combine(start_date, datetime.min.time()),
    # The start_date with the maximum possible time
    datetime.combine(start_date, datetime.max.time())
)
qs = qs.filter(start_date__range=start_date_range)

这篇关于Django过滤器基于日期的日期仅限于日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆