我有一个django模型:
class Measurement(models.Model):
"""
Saves the measurment data for every subdevice
"""
node = models.ForeignKey('Node', related_name='measurements')
value = models.CharField(_(u'Value'), max_length=255)
begin = models.DateTimeField(editable=True)
end = models.DateTimeField(editable=True)
现在值是True/False或00123这样的数字。现在我要做的是创建一个csv表:
Day, Time, node1, node2, node3
1, 00:00, 0, 1, 0
1, 00:05, 0, 1, 1
1, 00:10, 1, 0, 0
...
7, 24:00, 0, 0, 0
节点是像电视或桌面灯这样的设备。值(0/1)定义设备是否打开。开始/结束看起来像这样:
begin: 2012-12-01 00:00:00, end: 2012-12-01 08:32:33
现在我想知道的是如何检查时间/日期:2012-12-01 00:30的值?是否创建一个包含可能时间的列表:
times = [00:00, 00:05, ... 12:00, 12:05, ... 23:50, 23:55, 24:00]
遍历它并检查项是在begin还是end?我怎样才能最好地做到这一点?
以一种干净的方式迭代时间间隔很容易可以这样编写迭代器函数:
def itertime(start, end, int_step):
current_time = start
step = datetime.timedelta(0, int_step)
while current_time < end:
yield current_time
current_time += step
并在for
语句中使用它来获得时间测量为您的CSV文件的每一行:
for time in itertime(start_time, end_time, step=5 * 60):
...
现在,你需要的不是那么简单-它是棘手的,有一种感觉"老问题——必须考虑一下。"但让我试着总结一下你必须实现的步骤。我不能写代码,否则我就是在为你工作,尽管Python会邀请你
Read all the measurements you want to take in account
(use a simple query like Measurement.objects.filter(end__gte=begin_time,
begin__lte=end_time) )
get all the nodes in your query
for each node:
- get the initial state of each node at "begin_time" and annotate it in
a dictionary with the current state of each node
- calculate a "next_change" time in each node - determine the time
of next state change (either its begin, or its end, if the begin is in the past)
- push then into a n ordered data structure, such as a list
maintained with Python's heapq based on this
next_state_change" time-stamp
Then start your CSV files, with headers and first value line (from the dictionary
with the current state)
Loop through your time stamps along the snippet above, and for
each timestamp:
- pick measurements from your list until "nest_state_change" is
after your timestamp. For each of them:
- if "end" is in the future, annotate that as "next_state_change" and
push it back on the heapq
- update the device state on your nodes dictionary
- write a new row to your CSV file
就是这样。查看我的答案在这里:heapq与自定义比较谓词的实用方法来使用Python的heapq