I have a table called logs which has a datetime field. I want to select the date and count of rows based on a particular date format.
How do I do this using SQLAlchemy?
I have a table called logs which has a datetime field. I want to select the date and count of rows based on a particular date format.
How do I do this using SQLAlchemy?
我不知道通用的 SQLAlchemy 答案。大多数数据库支持某种形式的日期格式,通常通过函数。SQLAlchemy 支持通过 sqlalchemy.sql.func 调用函数。因此,例如,在 Postgres 后端使用 SQLAlchemy 和表 my_table(foo varchar(30), when timestamp) 我可能会做类似的事情
my_table = metadata.tables['my_table']
foo = my_table.c['foo']
the_date = func.date_trunc('month', my_table.c['when'])
stmt = select(foo, the_date).group_by(the_date)
engine.execute(stmt)
按截断为月份的日期分组。但请记住,在该示例中, date_trunc() 是 Postgres 日期时间函数。其他数据库会有所不同。你没有提到 underlyig 数据库。如果有一种独立于数据库的方式来做到这一点,我从来没有找到过。在我的情况下,我运行生产和测试 aginst Postgres 和单元测试 aginst SQLite,并在我的单元测试中使用 SQLite 用户定义函数来模拟 Postgress 日期时间函数。
Does counting yield the same result when you just group by the unformatted datetime column? If so, you could just run the query and use Python date's strftime() method afterwards. i.e.
query = select([logs.c.datetime, func.count(logs.c.datetime)]).group_by(logs.c.datetime)
results = session.execute(query).fetchall()
results = [(t[0].strftime("..."), t[1]) for t in results]
I don't know SQLAlchemy, so I could be off-target. However, I think that all you need is:
SELECT date_formatter(datetime_field, "format-specification") AS dt_field, COUNT(*)
FROM logs
GROUP BY date_formatter(datetime_field, "format-specification")
ORDER BY 1;
OK, maybe you don't need the ORDER BY, and maybe it would be better to re-specify the date expression. There are likely to be alternatives, such as:
SELECT dt_field, COUNT(*)
FROM (SELECT date_formatter(datetime_field, "format-specification") AS dt_field
FROM logs) AS necessary
GROUP BY dt_field
ORDER BY dt_field;
And so on and so forth. Basically, you format the datetime field and then proceed to do the grouping etc on the formatted value.