繁体   English   中英

SQLAlchemy 分组间隔 30 分钟

[英]SQLAlchemy group by interval 30 mins

我是 Python 和 SQL Alchemy 的新手,我有一个关于我正在尝试做的查询的问题。

更具体地说,我有这个数据列表。 它每 5 分钟包含一些措施。 我想做的是按时间戳分组,基于 30 分钟,所以当:

  • 00:15:00+00 -> 00:00:00+00
  • 00:20:00+00 -> 00:00:00+00
  • 00:30:00+00 -> 00:30:00+00
  • 00:35:00+00 -> 00:30:00+00
  • ETC

然后聚合该值的数据。

现在我有下面的代码:

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"

首先,我们必须弄清楚如何在 sql 中做到这一点。 获得半小时的间隔应该不会太难:

select 1800*(floor(unix_timestamp(timestamp)/1800))

您可能希望将其转换回日期时间,但恐怕这还不够便携。 在 mysql 中,您可以使用 from_unixtime,但如果您得到 unix 时间戳作为查询的结果,您可以轻松地将其转换为 python 中所需的任何内容。

其次,在sqlalchemy中怎么做。 看起来很简单:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM