[英]SQLAlchemy group by interval 30 mins
I am pretty new in Python and SQL Alchemy and I have a question about a query that I am trying to do.我是 Python 和 SQL Alchemy 的新手,我有一个关于我正在尝试做的查询的问题。
More specifically I have this data list.更具体地说,我有这个数据列表。 It contains some measures every 5 mins.
它每 5 分钟包含一些措施。 What I would like to do is to group by timestamp, based on 30 mins, so when:
我想做的是按时间戳分组,基于 30 分钟,所以当:
and then aggregate the data on that value.然后聚合该值的数据。
Now I have the code below:现在我有下面的代码:
base_query = (
db.query(
MyTable.timestamp,
func.max(MyTable.dual).label("max"),
func.min(MyTable.dual).label("min"),
func.avg(MyTable.dual).label("avg"),
func.count(MyTable.id).label("count"),
)
.join(Simulation, Simulation.id == MyTable.simulation_id)
.filter(
and_(MyTable.dual > 0, Simulation.scenario_id == scenario_id)
)
.group_by(MyTable.timestamp)
.order_by(MyTable.timestamp)
)
timestamp count avg
"2020-01-13 00:00:00+00" "10" "6454.70683325249"
"2020-01-13 00:05:00+00" "10" "6454.70683325249"
"2020-01-13 00:10:00+00" "10" "6454.70683325249"
"2020-01-13 00:15:00+00" "10" "6454.70683325249"
"2020-01-13 00:20:00+00" "10" "6454.70683325249"
"2020-01-13 00:25:00+00" "10" "6454.70683325249"
"2020-01-13 00:30:00+00" "10" "6454.70683325249"
"2020-01-13 00:35:00+00" "10" "6454.70683325249"
"2020-01-13 00:40:00+00" "10" "6454.70683325249"
"2020-01-13 00:45:00+00" "10" "6454.70683325249"
"2020-01-13 00:50:00+00" "10" "6454.70683325249"
"2020-01-13 00:55:00+00" "10" "6454.70683325249"
"2020-01-13 01:00:00+00" "10" "6454.70683325249"
"2020-01-13 01:05:00+00" "10" "6454.70683325249"
"2020-01-13 01:10:00+00" "10" "6454.70683325249"
"2020-01-13 01:15:00+00" "10" "6454.70683325249"
Firstly, we must figure out how to do it in sql.首先,我们必须弄清楚如何在 sql 中做到这一点。 Getting half an hour intervals should not be too difficult:
获得半小时的间隔应该不会太难:
select 1800*(floor(unix_timestamp(timestamp)/1800))
You might want convert this back to datetime, but I am afraid that's not portable enough.您可能希望将其转换回日期时间,但恐怕这还不够便携。 In mysql you can use from_unixtime, but if you get the unix timestamp as the result of the query, you can easily convert it to anything you want in python.
在 mysql 中,您可以使用 from_unixtime,但如果您得到 unix 时间戳作为查询的结果,您可以轻松地将其转换为 python 中所需的任何内容。
Secondly, how to do it in sqlalchemy.其次,在sqlalchemy中怎么做。 It looks like it is pretty straightforward:
看起来很简单:
import sqlalchemy
from sqlalchemy import select, func
q = select([
(1800*func.floor(func.unix_timestamp(t.c.tm0)/1800)).label("tm_hh")
]))
print(q)
# prints out this:
# SELECT %s * floor(unix_timestamp(T.tm0) / %s) AS tm_hh \nFROM T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.