querying for timestamp field in django
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.DateTime开发者_JS百科Field(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.....
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!
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.
精彩评论