ndb query error with datetime field - Google App Engine

Oscar Parra picture Oscar Parra · Feb 19, 2013 · Viewed 7.6k times · Source

I'm having a problem and I don't find any information about.

I define a field in my model like this.

class Dates(ndb.model):
    ...
    date = ndb.DateTimeProperty(required = True) # I want to store date and time
    ...

Later I try a query (now I want all the dates for a day, I don'tn mind the time):

kl = Dates.query(ndb.AND(Dates.date.year == year,
                         Dates.date.month == month,
                         Dates.date.day == day),
                 ancestor = customer.key).fetch(keys_only = True)
dates = ndb.get_multi(kl)

But I get this error log: AttributeError: 'DateTimeProperty' object has no attribute 'year'

I don't know why. I've tried Dates.date() == date, Dates.date == date (<-DateTime obj), ...

My DB is still empty but I suppose this doesn't mind because I'll never have dates for every possible days.

Anybody knows why? Should I go with GQL instead?

Answer

Dmytro Sadovnychyi picture Dmytro Sadovnychyi · Feb 19, 2013

You can use "range" queries for this. See example below.

import datetime
date = datetime.datetime.strptime('02/19/2013', '%m/%d/%Y')
kl = Dates.query(
    ndb.AND(Dates.date >= date),
            Dates.date < date + datetime.timedelta(days=1))

Will fetch all datetime's with 02/19/2013.