比较 peewee 中的日期时间 sql Python

Compare datetime in peewee sql Python

显然,我无法比较 peewee SQL 中的日期。

START_DATE = datetime.datetime(2015, 7, 20, 0, 0, 0)    
customer_records = Customers.select().\
                    join(Current_Insurers, on=(Customers.current_insurer == Current_Insurers.id)).\
                    switch(Current_Insurers).\
                    join(Insurers, on=(Current_Insurers.insurer == Insurers.id)).\
                    where(Customers.pol_type == "PC" & \
                          Current_Insurers.effective_date ==  START_DATE )

其中CustomersCurrent_InsurersInsurers是三个class。结果总是 0 条记录。但是,如果我从 sql 中删除 datetime 条件并进行如下比较

 customer_records = Customers.select().\
                        join(Current_Insurers, on=(Customers.current_insurer == Current_Insurers.id)).\
                        switch(Current_Insurers).\
                        join(Insurers, on=(Current_Insurers.insurer == Insurers.id)).\
                        where(Customers.pol_type == "PC" 
for r in customer_records:
    if(r.current_insurer.effective_date == START_DATE):
        print(r.policy_id)

令人惊讶的是我们现在可以比较并打印出客户。

peeweesql中添加datetime条件需要怎么做?

非常感谢,

Apparently, I could not compare the date in the peewee SQL.

这是完全错误的。您真的认为图书馆 会坏掉吗??

问题是 Python 运算符优先级。您需要用括号将相等表达式括起来。所以你的 where 子句应该看起来像这样:

where((Customers.pol_type == "PC") & \
      (Current_Insurers.effective_date ==  START_DATE))

此外,通常只有当您有多个连接到单个模型时才需要调用 switch()

放在一起,您的查询应该是:

query = (Customers
         .select()
         .join(Current_Insurers, on=(Customer.current_insurer == Current_Insurers.id))
         .join(Insurers, on=(Current_Insurers.insurer == Insurer.id))
         .where(
             (Customers.pol_type == "PC") &
             (Current_Insurers.effective_date ==  START_DATE)))

我来这里是因为我遇到了同样的问题,后来又遇到了同样的问题。

我的问题的原因是 mariaDB 在原始插入完成时剥离了毫秒数,而 python/peewee 在后来的更新中传递了谓词中的毫秒数。很郁闷。