Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python django中时间戳字段的查询_Python_Django_Django Models_Django Views - Fatal编程技术网

Python django中时间戳字段的查询

Python django中时间戳字段的查询,python,django,django-models,django-views,Python,Django,Django Models,Django Views,在我看来,日期的格式如下s_date=20090106和e_date=20100106 该模型定义为 class Activity(models.Model): timestamp = models.DateTimeField(auto_now_add=True) 如何查询包含上述信息的时间戳字段 Activity.objects.filter(timestamp>=s_date and timestamp<=e_date) Activity.

在我看来,日期的格式如下
s_date=20090106
e_date=20100106

该模型定义为

     class Activity(models.Model):
          timestamp = models.DateTimeField(auto_now_add=True)
如何查询包含上述信息的时间戳字段

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

Activity.objects.filter(timestamp>=s_date and timestamp您必须将日期转换为
datetime.datetime
类的实例。为您的案例执行此操作的最简单方法是:

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)
享受吧!

这里有一个方法:

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)

请注意,首先需要使用
strtime
将字符串日期转换为python
datetime
对象。其次,需要使用
gte
lte
方法形成django查询。

否。不能使用>=和进行筛选