Skip to main content
 首页 » 编程设计

Python 日期时间

2025年05月04日7落叶无声

我有一个 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] 

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

请您参考如下方法:

以干净的方式遍历时间间隔很容易 - 你可以像这样写一个迭代器函数:

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