Home > front end >  how to filter by date with datetimefield in Django with MYSQL
how to filter by date with datetimefield in Django with MYSQL

Time:12-07

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.

CodePudding user response:

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)

  • Related