Request timestamp field in django

In my views, I have a date in the following format s_date=20090106ande_date=20100106

The model is defined as

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

how to request the timestamp above.

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

Thank.....

+3
source share
2 answers

You need to convert the date to an instance of the class datetime.datetime. The easiest way to do this for your case:

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 it!

+6
source

Here is 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 you need to use first strptimeto convert the date of the string to a python object datetime. Second, you need to use the methods gteand ltefor the formation of django request.

+2
source

Source: https://habr.com/ru/post/1744114/


All Articles