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

时间:2022-08-25 10:26:53

The result should be Date object

结果应该是Date对象

Since the day cannot be 'removed', set it to say, 1st day of the month.

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

Leaving only Month, Year

只留下一个月,一年

2 个解决方案

#1


23  

You can use following constructs to filter the Date column using either year or month:

您可以使用以下构造来使用年份或月份过滤Date列:

.filter(extract('year', Foo.Date) == 2012)
.filter(extract('month', Foo.Date) == 12)

And group_by is also possible:

而group_by也是可能的:

.group_by(sqlalchemy.func.year(Foo.Date), sqlalchemy.func.month(Foo.Date))

Now I haven't tested it, but I assume that this might be slow because these queries result in full table scans, therefore I suggest you invest some time and learn how to use composite columns.

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

#2


0  

if you declare your schema like this,

如果您声明这样的架构,

schema.Column('created', types.TIMESTAMP(), default=now()),

the function now() is defined in the same module which can be like this

函数now()在同一模块中定义,可以是这样的

def now():
    now_date = datetime.datetime.now()
    return now_date.replace(day=1)

as per group_by requirement, here is a method mentioned.

按照group_by的要求,这是一个提到的方法。

you can modify hour and other field similarly.

您可以类似地修改小时和其他字段。

#1


23  

You can use following constructs to filter the Date column using either year or month:

您可以使用以下构造来使用年份或月份过滤Date列:

.filter(extract('year', Foo.Date) == 2012)
.filter(extract('month', Foo.Date) == 12)

And group_by is also possible:

而group_by也是可能的:

.group_by(sqlalchemy.func.year(Foo.Date), sqlalchemy.func.month(Foo.Date))

Now I haven't tested it, but I assume that this might be slow because these queries result in full table scans, therefore I suggest you invest some time and learn how to use composite columns.

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

#2


0  

if you declare your schema like this,

如果您声明这样的架构,

schema.Column('created', types.TIMESTAMP(), default=now()),

the function now() is defined in the same module which can be like this

函数now()在同一模块中定义,可以是这样的

def now():
    now_date = datetime.datetime.now()
    return now_date.replace(day=1)

as per group_by requirement, here is a method mentioned.

按照group_by的要求,这是一个提到的方法。

you can modify hour and other field similarly.

您可以类似地修改小时和其他字段。