Home > OS >  How to filter the dates based on range for datetime in django
How to filter the dates based on range for datetime in django

Time:11-28

views.py

def index(request):
    if request.method == "POST":
        from_date = request.POST.get("from_date")
        f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d')
        print(f_date)
        to_date = request.POST.get("to_date")
        t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d')
        print(t_date)
        global get_records_by_date
        get_records_by_date = Scrapper.objects.all().filter(Q(start_time__range=f_date),Q(end_time__range=t_date))
        print(get_records_by_date)

I need to get the dates from the range start time and end time based on datetime field. When I run the script its showing TypeError at / 'datetime.datetime' object is not iterable. Is there any solution for particular issue

Table structure

CodePudding user response:

The __range lookup [Django-doc] expects a 2-tuple with the from and to datetime, so:

def index(request):
    if request.method == 'POST':
        from_date = request.POST.get('from_date')
        f_date = datetime.datetime.strptime(from_date, '%Y-%m-%d')
        to_date = request.POST.get('to_date')
        t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d')
        get_records_by_date = Scrapper.objects.filter(
            start_time__range=(f_date, t_date)
        )
        # …

I would however advise to work with a form to process and clean the input, and not use a global variable: global state, especially in a webserver is a very bad idea.

  • Related