REA_ANDREW
REA_ANDREW

Reputation: 10764

How can I query objects with a date field, using a specific month and year?

I need to make a gql query against a set of some objects which have a date field. I am very new to python and also the GAE so I am a bit igorant to this. I am looking in the documentation but cannot find quite what I am looking for. Basically I have made the following class method

Event.getEventsForMonth(cls, month,year):

So I am trying to query my object where the month and year of the date field fall in a specified range. I have tried to create a date object and use that for the comparison but I have had no joy so far.

dateto = str(year)+str(month+1)+"01"
datefrom = str(year)+str(month)+"01"
if month + 1 == 13:
    dateto = str(year+1)+"01"+"01"

query = GqlQuery("SELECT * FROM Event WHERE date >= :datefrom AND date <= :dateto", dateto=dateto, datefrom=datefrom)
return query

This method to me looks awful, as I am not very up on the core methods I can use from Python inline with the GQL Query.

Any help is appreciated

Cheers,

Andrew

Upvotes: 1

Views: 270

Answers (1)

Nick Johnson
Nick Johnson

Reputation: 101149

First, store your dates as DateProperty or DateTimeProperty instances in the datastore.

Then, you can do your query something like this:

def getEventsForMonth(self, month, year):
  start_date = datetime.datetime(year, month, 1)
  if month == 12:
    end_date = datetime.datetime(year + 1, 1, 1)
  else:
    end_date = datetime.datetime(year, month + 1, 1)
  return Events.all().filter('date >=', start_date).filter('date <=', end_date).fetch(1000)

Upvotes: 3

Related Questions