views:

86

answers:

1

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

+3  A: 

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)
Nick Johnson
timedelta does not accept an argument for months, I think it only goes as far as days! +1 for the implementation though thank you.
REA_ANDREW
I will answer shortly if I cannot find any more answers to show how to add months! :-)
REA_ANDREW
How about:if month == 12: end_date = datetime.datetime(month=1, year=year+1) - datetime.timedelta(days=1)else: end_date = datetime.datetime(month=month+1, year=year) - datetime.timedelta(days=1)
dannyroa
You're quite right. Answer updated.
Nick Johnson