Python 在过滤器 SQLAlchemy 中进行日期时间比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17868743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Doing DateTime Comparisons in Filter SQLAlchemy
提问by user1431282
I'm a bit confused about filtering in SQLAlchemy.
我对 SQLAlchemy 中的过滤有点困惑。
I currently am trying to filter out entries greater than 10 weeks, so I have
我目前正在尝试过滤掉超过 10 周的条目,所以我有
current_time = datetime.datetime.utcnow()
potential = session.query(Subject).filter(Subject.time < current_time - datetime.timedelta(weeks=10))
However, the potential.count()
always returns 0
.
但是,potential.count()
总是返回0
。
My theory is that I am not using the filter statement correctly because when I try to use a column that is not of type Column(DateTime())
but instead
我的理论是我没有正确使用过滤器语句,因为当我尝试使用不是类型的列Column(DateTime())
而是
Column(String(250))
列(字符串(250))
like
喜欢
potential = session.query(Subject).filter(Subject.string_field < current_time - datetime.timedelta(weeks=10))
SQLAlchemy will still not complain.
SQLAlchemy 仍然不会抱怨。
Also, when I do a manual check with
另外,当我进行手动检查时
curr_time - session.query(Subject).first().time > datetime.timedelta(weeks=10)
I get True
which implies that the count should not be 0
.
我明白True
这意味着计数不应该是0
.
Am I missing something obvious? Any help would be appreciated.
我错过了一些明显的东西吗?任何帮助,将不胜感激。
采纳答案by Ian Wilson
If you switch the <
to a >
you can get all subjects within the last ten weeks:
如果您切换<
到 a>
您可以在过去十周内获得所有科目:
current_time = datetime.datetime.utcnow()
ten_weeks_ago = current_time - datetime.timedelta(weeks=10)
subjects_within_the_last_ten_weeks = session.query(Subject).filter(
Subject.time > ten_weeks_ago).all()
Filter generates a WHERE
clause which includesresults matching the clause. So the results are not "filtered out" but are included.
过滤器生成一个WHERE
子句,其中包含与该子句匹配的结果。所以结果没有被“过滤掉”,而是被包括在内。