2015-09-02 63 views
1

我寫了下面的程序,以獲取包含有關22-Jan-1963後爲之誕生了用戶的信息我的數據庫的某些行:如何比較「peewee.DateField」與「datatime.date」?

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) 

但是當我運行此,輸出是不是我所期望的(我希望詹姆斯,史蒂夫和亞歷克斯輸出):

>>> ================================ 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 
>>> 

正如您在上面看到的,它仍然不正確。

我該怎麼辦?

回答

3

我完全不知道PeeWee,但鑑於Sqlite沒有本地日期時間格式(它將它模擬爲字符串),您可能需要嘗試將日期格式更改爲"%Y-%m-%d";這將自動作爲一個字符串正確排序,然後可以用於Sqlite。

+0

是的,你應該使用Y-M-d格式,以確保排序是正確的。 – coleifer

0

documentation,我建議

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 
) 

是啊,這是相當冗長......