在SQLAlchemy中按小时分组?
我该如何在SQLAlchemy中按日期时间列的小时部分对查询结果进行分组?
5 个回答
7
最近我需要用SqlAlchemy和MySQL做类似的事情,最后我使用了DATE_FORMAT(http://www.w3schools.com/sql/func_date_format.asp)来按小时、分钟和秒来分组。
.group_by(func.date_format(date_col, '%H:%i:%s'))
如果只想按小时分组,可以用 '%H'
,而不是 '%H:%I:%s'
。
19
这个方法适用于PostgreSQL数据库:
.group_by(func.date_trunc('hour', date_col))
17
如果我没记错的话,你首先需要从时间戳中提取出小时,然后才能按照这个小时进行分组。
query(extract('hour', timeStamp).label('h')).group_by('h')