SQLAlchemy datetime operations on server side

前端 未结 2 638
花落未央
花落未央 2021-01-24 02:06

I have a table with scheduled and past payments, and I need to find if there are any two charges made in the same week for the same user/contract.

select count(*         


        
相关标签:
2条回答
  • 2021-01-24 02:43

    If you need this only for DAYs (which are default intervals), then simply restating your SQL as:

    c2.due_time > ADDDATE(c1.due_time, - 7)
    

    can be written in SA terms as:

    filter(Charge.due_time > func.ADDDATE(OldCharge.due_time, -7))
    

    If you need to filter for different interval types (weeks, months, years), you probably need to write a custom SQL Construct compiler (see Custom SQL Constructs and Compilation Extension for more info).

    0 讨论(0)
  • 2021-01-24 02:43

    So, I ended up writing a custom date_diff() expression:

    class date_diff(expression.FunctionElement):
        type = Integer()
        name = 'age'
    
    @compiles(date_diff, 'default')
    def _default_date_diff(element, compiler, **kw):  # pragma: no cover
        return "DATEDIFF(%s, %s)" % (compiler.process(element.clauses.clauses[0]),
                                     compiler.process(element.clauses.clauses[1]),
                                     )
    @compiles(date_diff, 'mysql')
    def _my_date_diff(element, compiler, **kw):  # pragma: no cover
        return "DATEDIFF(%s, %s)" % (compiler.process(element.clauses.clauses[0]),
                                     compiler.process(element.clauses.clauses[1]),
                                     )
    
    @compiles(date_diff, 'sqlite')
    def _sl_date_diff(element, compiler, **kw):    # pragma: no cover
        return "julianday(%s) - julianday(%s)" % (compiler.process(element.clauses.clauses[0]),
                                                  compiler.process(element.clauses.clauses[1]),
                                                  )
    
    0 讨论(0)
提交回复
热议问题