如何将"peewee.DateField"与"datatime.date"进行比较?



我编写了下面的程序来获取数据库中包含22-Jan-1963之后出生的用户信息的一些行:

import datetime as dt
import peewee as pw
db = pw.SqliteDatabase('people.db')
class Person(pw.Model):
    name = pw.CharField()
    birthday = pw.DateField(formats=['%d-%b-%Y'])
    class Meta:
        database = db # This model uses the "people.db" database.
db.create_tables([Person])
bob = Person(name = 'Bob', birthday = '21-Jan-1960')
james = Person(name = 'James', birthday = '22-Jan-1965')
steve = Person(name = 'Steve', birthday = '20-Jan-1970')
alex = Person(name = 'Alex', birthday = '18-Jan-1975')
bob.save()
james.save()
steve.save()
alex.save()
for item in Person.select().where(Person.birthday > dt.date(1963,1,22)):
    print item.name,item.birthday, item.birthday > dt.date(1963,1,22)

但是当我运行这个时,输出不是我所期望的(我期望输出James, Steve和Alex):

>>> ================================ RESTART ================================
>>> 
Bob 1960-01-21 False
James 1965-01-22 True
Steve 1970-01-20 True
>>> 

那么,我在where()法中用"22-Jan-1963"代替dt.date(1963,1,22),现在的结果是:

>>> ================================ RESTART ================================
>>> 
James 1965-01-22 True
>>> 
如你所见,

仍然不正确。

我该怎么办?

我绝对不知道PeeWee,但是考虑到Sqlite没有原生日期时间格式(它模仿它作为字符串),你可能想尝试将日期格式更改为"%Y-%m-%d";这将自动被正确排序为字符串,这可能会在Sqlite中工作。

根据文档,我建议

other = dt.date(1963, 1, 22)
Person.select().where(
    Person.birthday.year >= other.year
).where(
    Person.birthday.year > other.year
    | Person.birthday.month >= other.month
).where(
    Person.birthday.year > other.year
    | Person.birthday.month > other.month
    | Person.birthday.day > other.day
)

相关内容

  • 没有找到相关文章

最新更新