Ticket #1423: mysql_date_trunc.diff

File mysql_date_trunc.diff, 1.8 KB (added by Geert Vanderkelen <geert@…>, 19 years ago)

svn diff against the magic-removal branch

  • base.py

     
    108111
    109112def get_date_trunc_sql(lookup_type, field_name):
    110113    # lookup_type is 'year', 'month', 'day'
    111     # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
    112     # MySQL doesn't support DATE_TRUNC, so we fake it by subtracting intervals.
    113     # If you know of a better way to do this, please file a Django ticket.
    114     # Note that we can't use DATE_FORMAT directly because that causes the output
    115     # to be a string rather than a datetime object, and we need MySQL to return
    116     # a date so that it's typecasted properly into a Python datetime object.
    117     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)]
    118     if lookup_type in ('year', 'month'):
    119         subtractions.append(" - interval (DATE_FORMAT(%s, '%%%%e')-1) day" % field_name)
    120     if lookup_type == 'year':
    121         subtractions.append(" - interval (DATE_FORMAT(%s, '%%%%m')-1) month" % field_name)
    122     return "(%s - %s)" % (field_name, ''.join(subtractions))
     114    fields = [ 'year','month','day','hour','minute','second']
     115    format = [ '%Y-','%m','-%d',' %H:','%i',':%s']
     116    format_def = [ '0000-','01','-01',' 00:','00',':00']
     117    sql = ''
     118    try:
     119        i = fields.index(lookup_type) + 1
     120    except ValueError:
     121        sql = field_name
     122    else:
     123        str = ''
     124        for f in format[:i]:
     125            str = str + f
     126        for f in format_def[i:]:
     127            str = str + f
     128        sql = "CAST(DATE_FORMAT(%s,'%s') AS DATETIME)" % (field_name, str)
     129    return sql
    123130
    124131def get_limit_offset_sql(limit, offset=None):
    125132    sql = "LIMIT "
Back to Top