Home > Software design >  Django Queryset filter datetimefield using time interval
Django Queryset filter datetimefield using time interval

Time:12-16

I've got a field in one model like:

class Sample(models.Model):
    created_at = models.DateTimeField(auto_now_add=True, blank=True)

this is what it's looks like if saved:

2022-12-13 13:00:29.84166 08
2022-12-13 14:00:29.84166 08
2022-12-13 15:00:29.84166 08
2022-12-14 13:00:29.84166 08
2022-12-14 14:00:29.84166 08
2022-12-14 15:00:29.84166 08

Is it possible to filter that by range of time? maybe similar to this?

Sample.objects.filter(created_at __range=["13:00", "15:00"])

I have tried this but it's not working

Sample.objects.filter(created_at__time__range=["13:00", "15:00"])

I want to get all the data that ranged with "13:00", "15:00" in different dates

CodePudding user response:

You can try this:

Sample.objects.filter(
    created_at__time__gte='13:00', created_at__time__lte='15:00'
)

CodePudding user response:

I think it is better to divide this DateTime field to DateField and TimeField (both support auto_now parameters), so it will be easier.

  • Related