如何从sqlalchemy的Date字段获取月份和年份?

use*_*977 15 python sql sqlalchemy

结果应该是Date对象

由于当天无法"删除",因此请将其设置为月份的第1天.

只留下一个月,一年

pla*_*aes 33

您可以使用下面的结构来筛选Date使用其中任何一列yearmonth:

.filter(extract('year', Foo.Date) == 2012)
.filter(extract('month', Foo.Date) == 12)
Run Code Online (Sandbox Code Playgroud)

并且group_by也是可能的:

.group_by(sqlalchemy.func.year(Foo.Date), sqlalchemy.func.month(Foo.Date))
Run Code Online (Sandbox Code Playgroud)

现在我还没有对它进行测试,但我认为这可能会很慢,因为这些查询会导致全表扫描,因此我建议您花些时间学习如何使用复合列.

  • 谢谢,我也在 group_by 中使用了 .filter(extract('year', Foo.Date) 。我认为 func.year 在 postgres 中不可用,不确定。 (2认同)
  • @user1608977 哎呀,似乎`func.year` 是特定于 MySQL 的:S (2认同)
  • @plaes不一定,您可以在此类表达式上建立索引,这最终可能会阻止 seq 扫描,即在 foo(extract('year' from bar)) 上创建索引 idx_foo_year (2认同)