Search code examples
djangodjango-querysetdjango-filter

Django - Filter objects by DateTimeField with a date range


I have a datetime field like below,

class Data(models.Model):
    time = models.DateTimeField(default=timezone.now)

I want to get the objects based on a date range from template form. I have seen ways to filter for DateField but not for DateTimeField. Can anyone help?


Solution

  • When you filter DateTime field, the value which is used to compare must has type of Python DateTime. You can use datetime.strptime to format DateTime variable from string, then apply operators like __gte __lte ... to filter.