簡體   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