Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to filter Django datetimefield by time component
from django.db import models
class TimeTransform(models.Transform):
lookup_name = 'time'
bilateral = True
def as_sql(self, compiler, connection):
lhs, params = compiler.compile(self.lhs)
return "cast(%s as time)" % lhs, params
models.DateTimeField.register_lookup(TimeTransform)
"""
Usage:
>>> MyModel.objects.filter(datetimefield__time=datetime.datetime(1970, 1, 1, 8, 15, 37))
Can also combine lookups:
>>> MyModel.objects.filter(datetimefield__time__range=(datetime.datetime(1970, 1, 1, 11, 30, 0),
datetime.datetime(1970, 1, 1, 14, 0, 0)))
# because lunchtime!
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.