views:

135

answers:

3

How do I group query results by the hour part of a datetime column in SQLAlchemy?

A: 
Group by func.date_trunc(literal('hour'), date_col)
jspcal
I didn't mention I'm using sqlite; date_trunc is postgres?
Dave
A: 

If I remember correctly you must first extract the hour from your timestamp and then you can group by that.

query(extract('hour', timeStamp)).group_by(hour)
Scott
It worked when I put quotes on hour.
Dave
Oops... yeah you will need to do that. I updated my example. Thanks for catching that.
Scott
A: 

You can also do it in Python. Assuming you have an ordered query_result :

from itertools import groupby

def grouper( item ): 
    return item.created.hour
for ( hour, items ) in groupby( query_result, grouper ):
    for item in items:
        # do stuff

This answer is adapted from an answer to a similar question here

Raben