如何在Django模型中存储基于时间的数据?

时间:2016-11-06 21:12:20

标签: python django django-models

我正在Django中构建一个Web应用程序。我有一个系统会每分钟向建筑物中有多少人发送信号。然后,我希望能够将建筑物(模型)的数据访问到例如将其显示在图表中(一小时内建筑物中的人数),或者查看有多少人,例如上周三下午5点30分。

如何将其构建为可以根据日期/时间查找数据的模型?

感谢。

1 个答案:

答案 0 :(得分:2)

你的问题非常模糊,所以很难给出详细的回复,但你总是可以尝试一下这个问题:

# models.py
class BuildingCount(models.Model):
    number_of_people = models.IntegerField()
    datetime_stamp = models.DateTimeField(auto_now_add=True)

然后信号创建模型:

b = BuildingCount(number_of_people=x)
b.save()

日期时间是一个连续字段,因此您最好在两个日期时间之间进行过滤,然后尝试在特定日期时间获取记录。以下是几个例子:

from datetime import datetime, timedelta

# All counts in the past week
now = datetime.now()
one_week_ago = now - timedelta(days=7)
results = BuildingCount.objects.filter(datetime_stamp__range=(one_week_ago, now))
for result in results:
    print (result.number_of_people)

# Last Wed 5.30pm
# filter over a 2 min window and return the first record
result = BuildingCount.objects.filter(datetime_stamp__range=(datetime(2016,11,2,17,29), datetime(2016,11,2,17,31))).first()
print (result.number_of_people)

希望这会有所帮助,或者如果您提供更多信息,我可能会进一步提供帮助......