how to filter by date with datetimefield in Django with MYSQL

Question:

Datetimefield in MYSQL cannot be filtered by date.

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

As docs, it could be filtered by date:

  qs = Data.objects.fitler(created_at__date__lte=datetime.date(2022, 1, 1))

It works fine with sqlite3, but it always return empty queryset with MYSQL.

Asked By: Mas Zero

||

Answers:

First you need to convert the date to a datetime object. In your case convert '2022-01-01' as:

from datetime import datetime

date_object = datetime.strptime("2022-01-01", "%Y-%m-%d")

# Then you can filter it as
qs = Data.objects.fitler(created_at__date__lte=date_object)

Answered By: ilyasbbu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.