Flask-sqlalchemy query datetime intervals

前端 未结 4 457
南笙
南笙 2021-01-12 20:57

I have defined a table with flask-sqlalchemy. Displayed below.

class Notes(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    notes = db.Column(         


        
4条回答
  •  有刺的猬
    2021-01-12 21:31

    Can also try

    from sqlalchemy import func, text
    
    @staticmethod
    def newest(num):
        return Notes.query.filter(Notes.added_at >= (func.date_sub(func.now(),  text('INTERVAL  8 HOUR')).order_by(desc(Notes.added_at)).limit(num)
    

    OR

    from datetime import datetime, timedelta
    from dateutil import tz 
    
    @staticmethod
    def newest(num):
        recent = datetime.now(tz=tz.tzlocal()) - timedelta(hours=8)
    
        return Notes.query.filter(Notes.added_at >= recent).order_by(desc(Notes.added_at)).limit(num)
    

提交回复
热议问题