【问题标题】:Group by date in a particular format in SQLAlchemy在 SQLAlchemy 中以特定格式按日期分组
【发布时间】:2010-09-18 00:22:39
【问题描述】:

我有一个名为日志的表,它有一个日期时间字段。 我想根据特定的日期格式选择日期和行数。

如何使用 SQLAlchemy 做到这一点?

【问题讨论】:

    标签: python sql sqlalchemy


    【解决方案1】:

    我不知道通用的 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 日期时间函数。

    【讨论】:

    • 正是我需要的......现在到 SQLite 手册中找到截断函数!我认为在我的情况下是STRFTIME('%Y-%m', when)
    【解决方案2】:

    当您仅按未格式化的日期时间列分组时,计数是否会产生相同的结果?如果是这样,您可以只运行查询,然后使用 Python 日期的 strftime() 方法。即

    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]
    

    【讨论】:

      【解决方案3】:

      我不知道 SQLAlchemy,所以我可能会脱靶。但是,我认为您所需要的只是:

      SELECT date_formatter(datetime_field, "format-specification") AS dt_field, COUNT(*)
          FROM logs
          GROUP BY date_formatter(datetime_field, "format-specification")
          ORDER BY 1;
      

      好的,也许您不需要 ORDER BY,也许重新指定日期表达式会更好。可能有替代方案,例如:

      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;
      

      等等等等。基本上,您格式化日期时间字段,然后继续对格式化值进行分组等。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多