Django ORM Syntax for 'LIKE' queries with respect to Datetime

Viewed 76

I have this table which has column "date" in the format "2021-03-12 08:12:44.350176". I want to compare a external date such as "2021-03-12 08:12:44"

I have tried this

new_date = datetime.datetime(2021, 3, 12, 8, 12, 44, tzinfo=<UTC>)

obj = Test.objects.filter(date__contains=new_date).all()

But it doesn't work, it returns empty sets. My goal is to fetch all the records against the new_date.

Is there a way to remove milliseconds or way to compare the two dates?

2 Answers

It seems you want to compare datetimes upto the second while truncating the milliseconds. You can do that (and similar) by using either Trunc [Django docs] or one of it's subclasses. For truncating to the seconds you can use TruncSecond for your purpose:

import datetime
from django.db.models.functions import TruncSecond
from django.utils import timezone


new_date = datetime.datetime(2021, 3, 12, 8, 12, 44, tzinfo=timezone.utc)

obj = Test.objects.annotate(
    trunc_date=TruncSecond(
        'date',
        tzinfo=timezone.utc
    )
).filter(trunc_date=new_date)

according to [Django Docs]:

date
For datetime fields, casts the value as date. Allows chaining additional field lookups. Takes a date value.

date means a datetime.date object.

so you can use __date for datetime fields.

Related