﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
26348	Add a __time lookup for DateTimeField	Simon Charette	Simon Charette	"Now that we've added the `__date` (#9596) lookup I think we should allow the same for the time part.

A good [https://www.reddit.com/r/django/comments/49p8dg/excluding_hours_range_ex_from_215am_to_5am_from_a/ usage example] would be:

{{{#!python
Event.objects.filter(
    datetime__time__range=(start_time, end_time),
)
}}}

To select all activities that occurred in a timezone aware time range.

Here's an implementation for PostgreSQL and MySQL missing tests:

{{{#!python
from django.conf import settings
from django.db import models
from django.utils import timezone
from django.utils.functional import cached_property


class DateTimeTimeTransform(models.Transform):
    lookup_name = 'time'

    @cached_property
    def output_field(self):
        return models.TimeField()

    def as_mysql(self, compiler, connection):
        lhs, lhs_params = compiler.compile(self.lhs)
        if settings.USE_TZ:
            lhs = ""CONVERT_TZ(%s, 'UTC', %%s)"" % lhs
            tzname = timezone.get_current_timezone_name()
            lhs_params.append(tzname)
        sql = ""TIME(%s)"" % lhs
        return sql, lhs_params

    def as_postgresql(self, compiler, connection):
        lhs, lhs_params = compiler.compile(self.lhs)
        if settings.USE_TZ:
            lhs = ""%s AT TIME ZONE %%s"" % lhs
            tzname = timezone.get_current_timezone_name()
            lhs_params.append(tzname)
        sql = ""(%s)::time"" % lhs
        return sql, lhs_params

models.DateTimeField.register_lookup(DateTimeTimeTransform)
}}}

We should wait for the datetime expression refactor (#25774) to land before proceeding with this patch."	New feature	closed	Database layer (models, ORM)	dev	Normal	fixed			Ready for checkin	1	0	0	0	0	0
