0

I have the following model field:

inbound_date = models.DateTimeField()

I want to filter on date, and not care about the time. I have inserted two test objects which return the following values for inbound_date:

2018-11-14 00:00:00+00:00
2018-11-15 08:37:09+00:00

But all my attempts at retrieving the objects fail:

AppInbound.objects.filter(inbound_date__date=datetime.date(2018, 11, 15))

Or

AppInbound.objects.filter(inbound_date__date='2018-11-15')

But all seem to return an empty QuerySet. The only one I did manage to get working was:

AppInbound.objects.filter(inbound_date__startswith='2018-11-15')

Which returns the the last objects, with datetime of 2018-11-15 08:37:09+00:00.

Can someone explain what is going wrong here?

It is an MySQL database, and we have TZ enabled.

Serena
  • 185
  • 1
  • 14

1 Answers1

0

You can try like this:

 AppInbound.objects.filter(inbound_date__lt=datetime.date(2018, 11, 15), inbound_date__gte=datetime.date(2018, 11, 14))  # will return objects for 14th November.

Or you can check this answer on how to filter on specific dates.

If you are only concerned with using date then DateField should be used here:

inbound_date = models.DateField()

Then you should be able to filter with date object(datetime.date).

ruddra
  • 50,746
  • 7
  • 78
  • 101
  • Changing the field to DateField is no option, I am not the only user of this db, I just happen to only need the date. According to the [docs](https://docs.djangoproject.com/en/2.1/ref/models/querysets/#date) you should be able to do `Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))` which is a lot easier than 2 filters, lt and gte. – Serena Nov 15 '18 at 15:37
  • You are right. I was able to work it in Postgresql. Maybe its an issue with timezone, because as per docs, *fields are converted to the current time zone before filtering*. Still, you can try with `(inbound_date__year='2018', inbound_date__month='11', inbound_date__day='15')` – ruddra Nov 15 '18 at 15:53
  • Does not work either. I have both a PostgreSQL db and a MySQL db connected, the PostgreSQL db works fine, MySQL not. It probably has something to do with the TZ. Thanks anyway. – Serena Nov 16 '18 at 12:45