1

我有一个如下所示的 SQLAlchemy 模型。

class ElUsage(Base):
    recid = Column(Integer(),primary_key=True)
    date_of_usage = Column(DATE())
    total_units = Column(Float(precision=5))

我试图通过将日期与熊猫日历进行比较来创建混合属性 is_holiday

@hybrid_property
def is_holiday(self):
    is_hday = 0
    cal = calendar()
    holidays = cal.holidays(start=dt.date(2015,1,1),
                            end=dt.date(2020,12,31))
    if np.datetime64(self.usage_date) in holidays:
        is_hday = 1
    
    return is_hday

@is_holiday.expression
def is_holiday(cls):
    is_hday = 0
    cal = calendar()
    holidays = cal.holidays(start=dt.date(2015,1,1),
                            end=dt.date(2020,12,31))
    
    if np.datetime64(cls.usage_date) in holidays:
        is_hday = 1
    
    return is_hday

显式转换为 numpy datetime64 是一项挑战。创建混合属性以将日期标记为假日或非(0 或 1)值的任何简单方法?

TIA

4

1 回答 1

1

考虑到这个答案,第一个属性 - python 部分 - 你做得对。

@hybrid_property
def is_holiday(self):
    is_hday = 0
    cal = calendar()
    holidays = cal.holidays(start=dt.date(2015,1,1),
                            end=dt.date(2020,12,31))
    if np.datetime64(self.usage_date) in holidays:
        is_hday = 1
    
    return is_hday

第二部分 - SQL 部分 - 更复杂,因为您需要编写返回等效属性的 SQLAlchemy 查询

@is_holiday.expression
def is_holiday(cls):
    cal = calendar()
    holidays = cal.holidays(start=dt.date(2015,1,1),
                            end=dt.date(2020,12,31))
    return cls.usage_date.in_(holidays)

我无法对此进行测试,所以如果它不起作用,请告诉我。

于 2020-10-09T08:06:04.187 回答