views:

129

answers:

2

In my views i have the date in the following format s_date=20090106 and e_date=20100106

The model is defined as

     class Activity(models.Model):
          timestamp = models.DateTimeField(auto_now_add=True)

how to query for the timestamp filed with the above info.

   Activity.objects.filter(timestamp>=s_date and timestamp<=e_date)

Thanks.....

+2  A: 

You have to convert your date to an instance of datetime.datetime class. Easiest way to do it for your case is:

import datetime

#
# This creates new instace of `datetime.datetime` from a string according to
# the pattern given as the second argument.
#
start = datetime.datetime.strptime(s_date, '%Y%m%d')
end = datetime.datetime.strptime(e_date, '%Y%m%d')

# And now the query you want. Mind that you cannot use 'and' keyword
# inside .filter() function. Fortunately .filter() automatically ANDs
# all criteria you provide.
Activity.objects.filter(timestamp__gte=start, timestamp__lte=end)

Enjoy!

Bartosz
Thanks........................
Hulk
No. You can't do filters with >= and <=. Filter arguments are keywords, not expressions. -1.
Daniel Roseman
Valid point. Updated.
Bartosz
+2  A: 

Here's one way:

s_date = datetime.strptime('20090106', '%Y%m%d')
e_date = datetime.strptime('20100106', '%Y%m%d')
Activity.objects.filter(timestamp__gte=s_date, timestamp__lte=e_date)

Note that first you need to use strptime to convert your string date to a python datetime object. Second, you need to use the gte and lte methods to form a django query.

ars