Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy group by minute

The task is a grouping of datetime values (using SQLAlchemy) into per minute points (group by minute).

I have a custom SQL-query:

SELECT COUNT(*) AS point_value, MAX(time) as time
  FROM `Downloads` 
  LEFT JOIN Mirror ON Downloads.mirror = Mirror.id 
 WHERE Mirror.domain_name = 'localhost.local' 
   AND `time` BETWEEN '2012-06-30 00:29:00' AND '2012-07-01 00:29:00'
 GROUP BY DAYOFYEAR( time ) , ( 60 * HOUR( time ) + MINUTE(time ))
 ORDER BY time ASC

It works great, but now I have do it in SQLAlchemy. This is what I've got for now (grouping by year is just an example):

rows = (DBSession.query(func.count(Download.id), func.max(Download.time)).
    filter(Download.time >= fromInterval).
    filter(Download.time <= untilInterval).
    join(Mirror,Download.mirror==Mirror.id).
    group_by(func.year(Download.time)).
    order_by(Download.time)
)

It gives me this SQL:

SELECT count("Downloads".id) AS count_1, max("Downloads".time) AS max_1 
FROM "Downloads" JOIN "Mirror" ON "Downloads".mirror = "Mirror".id 
WHERE "Downloads".time >= :time_1 AND "Downloads".time <= :time_2 
GROUP BY year("Downloads".time) 
ORDER BY "Downloads".time

As you can see, it lacking only the correct grouping:

GROUP BY DAYOFYEAR( time ) , ( 60 * HOUR( time ) + MINUTE(time ))

Does SQLAlchemy have some function to group by minute?

like image 623
Nikolay Baluk Avatar asked Feb 24 '26 12:02

Nikolay Baluk


1 Answers

You can use any SQL side function from SA by means of Functions, which you already use fr the YEAR part. I think in your case you just need to add (not tested):

from sqlalchemy.sql import func
...
# add another group_by to your existing query:
rows = ...
group_by(func.year(Download.time), 
         60 * func.HOUR(Download.time) + func.MINUTE(Download.time)
)
like image 122
van Avatar answered Feb 26 '26 06:02

van