Ebrahim Ghasemi
Ebrahim Ghasemi

Reputation: 6116

How to compare "peewee.DateField" with "datatime.date"?

I wrote the below program to fetch some rows of my database that contain information about the users whom born after 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)

But when I run this, output is not what I have expected (I expect James, Steve and Alex in the output):

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

Well, I replaced dt.date(1963,1,22) with "22-Jan-1963" in the where() method, and now the result is:

>>> ================================ RESTART ================================
>>> 
James 1965-01-22 True
>>> 

As you see above, it is not correct still.

What shall I do?

Upvotes: 2

Views: 6071

Answers (2)

Yushin Washio
Yushin Washio

Reputation: 733

Following the documentation, I’d suggest

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
)

Yeah, it’s quite verbose...

Upvotes: 4

user707650
user707650

Reputation:

I absolutely do not know PeeWee, but given that Sqlite does not have a native date-time format (it mimics it as a string), you may want to try and change the date format to "%Y-%m-%d"; this will automatically be sorted correctly as a string, which may then work for Sqlite.

Upvotes: 4

Related Questions