【发布时间】:2015-06-21 15:32:11
【问题描述】:
我需要执行一个查询,该查询仅比较 TIMESTAMP 列中的年份和月份值,其中记录如下所示:
2015-01-01 08:33:06
SQL 查询非常简单(有趣的部分是 year(timestamp) 和 month(timestamp) 提取年份和月份以便我可以使用它们比较:
SELECT model, COUNT(model) AS count
FROM log.logs
WHERE SOURCE = "WEB"
AND year(timestamp) = 2015
AND month(timestamp) = 01
AND account = "TEST"
AND brand = "Nokia"
GROUP BY model
ORDER BY count DESC limit 10
现在的问题:
这是我的 SQLAlchemy 查询:
devices = (db.session.query(Logs.model, Logs.timestamp,
func.count(Logs.model).label('count'))
.filter_by(source=str(source))
.filter_by(account=str(acc))
.filter_by(brand=str(brand))
.filter_by(year=year)
.filter_by(month=month)
.group_by(Logs.model)
.order_by(func.count(Logs.model).desc()).all())
部分:
.filter_by(year=year)
.filter_by(month=month)
和
不一样AND year(timestamp) = 2015
AND month(timestamp) = 01
我的 SQLAchemy 查询不工作。 year 和 month 似乎是从时间戳列中提取值的 MySQL 函数。
我的数据库模型如下所示:
class Logs(db.Model):
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.TIMESTAMP, primary_key=False)
.... other attributes
有趣的是,当我选择并打印Logs.timestamp 时,它的格式如下:
(datetime.datetime(2013, 7, 11, 12, 47, 28))
如果我希望我的 SQLAlchemy 查询按 DB Timestamp 年份和月份进行比较,这部分应该如何用 SQLAlchemy 编写?
.filter_by(year=year) #MySQL - year(timestamp)
.filter_by(month=month) #MySQL- month(timestamp)
我尝试了.filter(Logs.timestamp == year(timestamp) 和类似的变体,但没有运气。任何帮助将不胜感激。
【问题讨论】:
标签: python mysql date sqlalchemy