| 127 | | # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html |
|---|
| 128 | | # MySQL doesn't support DATE_TRUNC, so we fake it by subtracting intervals. |
|---|
| 129 | | # If you know of a better way to do this, please file a Django ticket. |
|---|
| 130 | | # Note that we can't use DATE_FORMAT directly because that causes the output |
|---|
| 131 | | # to be a string rather than a datetime object, and we need MySQL to return |
|---|
| 132 | | # a date so that it's typecasted properly into a Python datetime object. |
|---|
| 133 | | subtractions = ["interval (DATE_FORMAT(%s, '%%%%s')) second - interval (DATE_FORMAT(%s, '%%%%i')) minute - interval (DATE_FORMAT(%s, '%%%%H')) hour" % (field_name, field_name, field_name)] |
|---|
| 134 | | if lookup_type in ('year', 'month'): |
|---|
| 135 | | subtractions.append(" - interval (DATE_FORMAT(%s, '%%%%e')-1) day" % field_name) |
|---|
| 136 | | if lookup_type == 'year': |
|---|
| 137 | | subtractions.append(" - interval (DATE_FORMAT(%s, '%%%%m')-1) month" % field_name) |
|---|
| 138 | | return "(%s - %s)" % (field_name, ''.join(subtractions)) |
|---|
| | 127 | fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] |
|---|
| | 128 | format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. |
|---|
| | 129 | format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') |
|---|
| | 130 | try: |
|---|
| | 131 | i = fields.index(lookup_type) + 1 |
|---|
| | 132 | except ValueError: |
|---|
| | 133 | sql = field_name |
|---|
| | 134 | else: |
|---|
| | 135 | format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]]) |
|---|
| | 136 | sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) |
|---|
| | 137 | return sql |
|---|