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
将字符串日期转换为pythondatetime
对象。其次,需要使用gte
和lte
方法形成django查询。否。不能使用>=和进行筛选