mysql - 比较peewee sql Python中的日期时间

标签 mysql datetime python-3.x peewee

显然,我无法比较 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)

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

peewee sql中添加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)))

关于mysql - 比较peewee sql Python中的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32563411/

相关文章:

PHP JSON : print blank page when result is empty

mysql - MySQL 中的累计计数 (*)

python - 为 Pandas 数据框中的每个日期时间添加多行

python - 如何在python3中将类自变量作为Thread的参数传递?

python - namedtuple 需要 3 个参数?

python - 根据列表创建给定字符串的所有可能组合

mysql - mySQL 查询中的交叉引用表?

php - 将月拆分为周并使用 GROUP BY

SQL 服务器 : group by a function on a field an select that

mysql - 使用 SELECT 查询的结果作为 INSERT 查询中的值