Query with dates using a range

0

I have the following query:

query=Detalles.objects.filter(fecha_creacion__range=(fecha_inicio,fecha_final))

The expected result is to filter the results between date A and date B, that is:

fechaA= 01-07-2018 FechaB=04-07-2018

However, the query only returns until 03-07-2018, that is until a day before.

To return until 04-07-2018 it is necessary to pass a date later, that is, put 05-07-2018 to return until 04-07-2018.

Range takes all the values between FechaA and FechaB but I do not know if I need to specify something more or how can I improve the query better.

Edited

fecha_inicio = request.GET.get('fechaA')
fecha_final  = request.GET.get('fechaB') 


time.min
datetime.time(0, 0)

time.max
datetime.time(23, 59, 59, 999999)

fecha_inicio = datetime.combine(fecha_inicio, time.min)
fecha_final = datetime.combine(fecha_final, time.max)
    
asked by Noel L 04.07.2018 в 22:40
source

1 answer

1

Now I see what the problem is. I think it's right that you use a DateTimeField for creation dates. The problem is that you are using dates type date : 01-07-2018 and 04-07-2018 . What you should be using are dates of type datetime that include the time.

Imagine you have this:

>>> from datetime import date
>>> fecha_inicio = date(2018, 7, 1)
>>> fecha_final = date(2018, 7, 4)

What will happen when you pass it through the query is that you will add a 00:00:00 (I'm not sure if this is done by Django or the database engine, you should confirm it). Therefore, in your query you would have: 2018-07-01 00:00:00 and 2018-07-04 00:00:00 respectively.

For the case of the initial date 2018-07-01 00:00:00 would be good because you are searching from the beginning of the day, but for the case of the final date 2018-07-04 00:00:00 you would be looking only until the first minute of day 04. That is why you have no results for that day.

The solution is to use datetime.combine :

>>> from datetime import date, datetime, time
>>> fecha_inicio = date(2018, 7, 1)
>>> fecha_final = date(2018, 7, 4)
>>> print fecha_inicio
2018-07-01
>>> print fecha_final
2018-07-04
>>> time.min
datetime.time(0, 0)
>>> time.max
datetime.time(23, 59, 59, 999999)
>>> fecha_inicio = datetime.combine(fecha_inicio, time.min)
>>> fecha_final = datetime.combine(fecha_final, time.max)
>>> print fecha_inicio
2018-07-01 00:00:00
>>> print fecha_final
2018-07-04 23:59:59.999999

Using datetime.time.min and datetime.time.max , which represent the first and last hour of the day, we have "combined" the dates to use these values. Now I am sure that your query will work as we are using until the last minute of day 4.

    
answered by 04.07.2018 в 23:10