Group by hour in SQLAlchemy?

后端 未结 5 727
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 10:43

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

相关标签:
5条回答
  • 2020-12-15 11:24

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

    query(extract('hour', timeStamp).label('h')).group_by('h')
    
    0 讨论(0)
  • 2020-12-15 11:31

    This works for PostgreSQL:

    .group_by(func.date_trunc('hour', date_col))
    
    0 讨论(0)
  • 2020-12-15 11:38

    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

    0 讨论(0)
  • 2020-12-15 11:39

    Recently I had to do a similar thing using SqlAlchemy and MySQL and ended up using the DATE_FORMAT (http://www.w3schools.com/sql/func_date_format.asp) to group by hour, minute, second

    .group_by(func.date_format(date_col, '%H:%i:%s'))
    

    To only group by hour it would be '%H' instead of '%H:%I:%s'

    0 讨论(0)
  • 2020-12-15 11:40

    In Oracle, use func.trunc(MyTable.dt, 'HH')

    It is a bit finicky, however. This fails:

    q = session.query(func.trunc(MyTable.dt, 'HH'), func.sum(MyTable.qty) \
               .group_by(func.trunc(MyTable.dt, 'HH'))
    

    But this succeeds:

    trunc_date = func.trunc(MyTable.dt, 'HH')
    q = session.query(trunc_date, func.sum(MyTable.qty) \
               .group_by(trunc_date)
    

    Thanks to this thread for the tip.

    0 讨论(0)
提交回复
热议问题