python - 在django中查询时间戳字段

标签 python django django-models django-views

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

模型定义为

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

如何查询包含上述信息的时间戳。

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

谢谢.....

最佳答案

您必须将日期转换为 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)

尽情享受吧!

关于python - 在django中查询时间戳字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2771739/

相关文章:

python - 根据条件删除 pandas 数据框的行

python - 在提取/分解一些 'td' 标签后,无法访问超出表第一行的 'td' 标签

python - 使用 django-import-export 反向外键

Django反向ForeignKey查找返回None

Django 模型重写保存方法

python,没有得到完整的响应

python - 如何检查一个元素是否存在于 Python 数组中(相当于 PHP in_array)?

Django FileField url不是相对的

mysql - Django - 操作错误 : (2006, 'MySQL server has gone away')

django - 如何使Django应用程序可插入?