Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by hour in SQLAlchemy?

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

like image 969
Dave Avatar asked Jan 21 '10 22:01

Dave


People also ask

How do I use GroupBy in SQLAlchemy?

Implementing GroupBy and count in SQLAlchemy Get the books table from the Metadata object initialized while connecting to the database and pass the SQL query to the execute() function and get all the results using fetchall() function and use a for loop to iterate through the results.

What is lazy true in SQLAlchemy?

Lazy parameter determines how the related objects get loaded when querying through relationships. Below listed are the four main lazy parameters. Typically when you query the database, the data get loaded at once; however, lazy parameter allows you to alternate the way they get loaded. lazy = 'select' (or True)

What is an SQLAlchemy Session?

The SQLAlchemy ORM is based around the concept of an identity map such that when an object is “loaded” from a SQL query, there will be a unique Python object instance maintained corresponding to a particular database identity.

Is SQLAlchemy between inclusive?

Using a SQL BETWEEN operator will evaluate ranges in an inclusive manner.


2 Answers

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'

like image 88
svavarm Avatar answered Sep 18 '22 22:09

svavarm


This works for PostgreSQL:

.group_by(func.date_trunc('hour', date_col))
like image 33
jspcal Avatar answered Sep 20 '22 22:09

jspcal