[Django]-Querying for timestamp field in django

6👍

✅

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!

2👍

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.

Leave a comment