Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading