2

我有一个 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 at 00:30 ?我是否创建一个包含可能时间的列表:

times = [00:00, 00:05, ... 12:00, 12:05, ... 23:50, 23:55, 24:00]

遍历它并检查项目是在开始还是结束?我怎样才能最好地做到这一点?

4

1 回答 1

0

以干净的方式迭代时间间隔很容易 - 你可以编写一个迭代器函数,如下所示:

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 文件每一行的 tme 测量值:

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 with custom compare predicate是一种使用 Python 的 heapq 的实用方法

于 2013-03-12T13:13:26.737 回答