Filtering Object by Date Range

I have a list of task object that has a start_date and I want to query it by start_date range

For instance

start_date = "2021-04-04" #Sample Date 
end_date = "2021-04-05" # Sample Date

task_history = TaskEmployeeHistory.objects.filter(
employee=employee, start_date__range=[start_date, end_date])

sample_response = [
            "id": 24,
            "start_date": "Apr 05, 2021 03:39:57 PM",
            "end_date": "Apr 05, 2021 03:40:11 PM",
            "employee_name": "User 1"
            "id": 26,
            "start_date": "Apr 06, 2021 05:39:54 PM",
            "end_date": "Apr 06, 2021 05:40:05 PM",
            "employee_name": "User 3"

Basically, I want to exclude the April 6, and only want the first item on the list (since the range of the start date is from April 4 to April 5 only), but the task_history returns empty QuerySet, why does it happened?

Hi Clark,

It’s not immediately clear from your post what the data type is of start_date and end_date on your model. Is it a DateTimeField?

Not Django specific, but my first suspicion in a case like this (I’ve fallen in this trip quite often myself :slight_smile: ):
When comparing a “date” with a “date+time”, the date will often internally be converted to 00:00:00 (i.e. midnight in the morning) prior to the filtering.

If this is the case, your range of 2021-04-04 ~ 2021-04-05 in reality becomes: 2021-04-04 00:00:00.000 up to 2021-04-05 00:00:00.000, which would exclude the first response.
Could you maybe try to intentionally set your end_date to 2021-04-06 to see if that does include the first entry? If so, the above conversion is what is happening - and you just always want to set your end date a day later.

If this is not the case, there might be issues related to timezones at play - but maybe worth trying the above first.

Cheers, Ad

1 Like