我已经用 flask-sqlalchemy 定义了一个表。显示如下。
class Notes(db.Model):
id = db.Column(db.Integer, primary_key=True)
notes = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
added_at = db.Column(db.DateTime, default=db.func.now())
@staticmethod
def newest(num):
return Notes.query.order_by(desc(Notes.added_at)).limit(num)
我正在尝试编写一个查询来替换现有的直接查询,如下所示。
select notes,user,added_at from notes where added_at >= now() - INTERVAL 8 HOUR;
但是,根据我能找到的文档,我无法找到执行相同操作的方法。我能够进行更简单的查询,但我正在努力重新创建 sql 本身非常简单的内容。
我非常愿意阅读有关它的一些文档,但也无法准确地确定下来。你能提供的任何方向都会很棒。
最佳答案
我总是使用 Python 的 datetime
库获取“现在”和“8 小时前”,然后使用日期时间进行过滤:
from datetime import datetime, timedelta
now = datetime.now()
eight_hours_ago = now - timedelta(hours=8)
Notes.query.filter(Notes.added_at > eight_hours_ago).filter(Notes.added_at < now).all()
关于python - Flask-sqlalchemy 查询日期时间间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495935/