Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy: applying an SQL-like date() function on a datetime column

I would like to group by date and count the resulting number of id's using sqlalchemy.

Unfortunately, my column containing date information created_datetime is a datetime and I would like to use an sql function like

group by date(created_datetime)

in order to group by date.

Here is what I have so far...

conn = engine.connect()

s = my_db.my_table.alias()

q = select([s.c.id]).\
    group_by(s.c.created_datetime).\
    count()

result = conn.execute(q)

for i in result:
    print(i)

conn.close()
like image 520
user3439329 Avatar asked Mar 31 '14 22:03

user3439329


1 Answers

Use sqlalchemy.sql.functions.func for this:

from sqlalchemy.sql import func

q = select([s.c.id]).\
    group_by(func.date(s.c.created_datetime)).\
    count()
like image 193
van Avatar answered Nov 19 '22 18:11

van