gpt4 book ai didi

python - SQLAlchemy MySQL 时间戳列值

转载 作者:行者123 更新时间:2023-11-29 00:01:21 29 4
gpt4 key购买 nike

我需要执行一个查询,该查询仅比较 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 查询不工作。 yearmonth 似乎是从时间戳列中提取值的 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 查询按数据库时间戳年份和月份进行比较,这部分应该如何在 SQLAlchemy 中编写?

 .filter_by(year=year)  #MySQL - year(timestamp)
.filter_by(month=month) #MySQL- month(timestamp)

我尝试了 .filter(Logs.timestamp == year(timestamp) 和类似的变体,但没有成功。任何帮助将不胜感激。

最佳答案

简单替换:

 .filter_by(year=year)
.filter_by(month=month)

与:

from sqlalchemy.sql.expression import func
# ...

.filter(func.year(Logs.timestamp) == year)
.filter(func.month(Logs.timestamp) == month)

SQL and Generic Functions 中阅读更多相关信息文档部分。

关于python - SQLAlchemy MySQL 时间戳列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654181/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com