Flask-SQLAlchemy查询日期时间间隔 [英] Flask-sqlalchemy query datetime intervals
问题描述
我用flask-sqlalchemy定义了一个表.显示在下面.
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(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)
我正在尝试编写一个要替换的查询,而该查询已经存在,看起来像这样.
I'm attempting to write a query that is to replace and already existing direct query, which looks like this.
select notes,user,added_at from notes where added_at >= now() - INTERVAL 8 HOUR;
但是,根据我可以找到的文档,我无法找到一种执行此操作的方法.我可以进行更简单的查询,但是我正在努力重新创建sql本身非常简单的内容.
However based on the documentation that I can find, I'm not able to find a method to do the same. I'm able to make simpler queries, but I'm struggling to recreate what's pretty simple in sql itself.
我非常愿意阅读有关它的一些文档,也无法精确地确定它们.您可以提供的任何方向都很棒.
I'm more than willing to read some documentation surrounding it, wasn't able to precisely nail that down either. Any direction you could provide would be awesome.
推荐答案
我一直都有Python的datetime
库为我提供现在"和"8小时前"的信息,然后使用日期时间进行过滤:
I always have Python's datetime
library get me the "now" and "8 hours ago", then just do a filter using the datetimes:
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()
这篇关于Flask-SQLAlchemy查询日期时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!