python - Flask-sqlalchemy 查询日期时间间隔

标签 python flask-sqlalchemy

我已经用 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/

相关文章:

python - 将 Python 的默认数值表示设置为 "Decimal"

python - OpenCv 版本 3 缺少一些 python 绑定(bind)?

python - Tkinter.Text 索引表达式和 unicode

python - Discord.py 机器人将消息重新发送到另一个 channel ,添加 react 后会中断

python - 如何更新 Flask-SQLAlchemy 关联表?

python - 无法删除表,因为其他对象依赖于它

python - Flask SQLAlchemy 分页错误

python - 如何使用 numpy.polyfit 查找斜率和截距误差

python - 全局名称 'unhex' 未定义

flask - '没有找到应用程序。要么在 View 函数内工作,要么推送'RuntimeError : No application found