我正在尝试计算从创建和更新文件到当前时刻的时间差,以计算丢失数据的数量。但我无法正确减去它们。我的代码如下。
文件中的数据如下所示:
DATE,temp1
2017-08-14 17:10:01,0.44
2017-08-14 17:15:01,0.62
2017-08-14 17:20:01,0.99
2017-08-14 17:25:01,0.85
2017-08-14 17:30:01,0.13
2017-08-14 17:35:01,0.24
2017-08-14 17:40:02,0.95
2017-08-14 17:45:01,0.65
代码是:
#!/usr/bin/env python
# -*-coding:utf-8 -*
import os
import sys
import time
from time import mktime, strftime, localtime, sleep
from datetime import datetime, timedelta
def missing_data(expect, missed):
.
.
.
.
def main():
fmt = '%Y-%m-%d %H:%M:%S'
with open('/home/kamil/Desktop/sensor1/temp.dat', 'rb') as f:
read = f.readlines()[1:]
for line in read:
line = line.strip().split(',')
# print line
start_date = line[0] # type is str so i convert it to datetime
start_date = datetime.strptime(start_date, fmt) # type is datetime.datetime and here I need the first timestamp in the file only
current_time = datetime.now()
step_size = 5
differ_time = current_time - start_date
minutes_values = differ_time.total_seconds() / 60
print 'minutes_values:::::::::::::::::::', minutes_values
missed = int(minutes_values / step_size)
expected = .........
missing_data(expected, missed)
if __name__ == '__main__':
main()
如果我打印minutes_values,它会给我这样的结果:
40.755
35.7553
30.755
25.755
20.755
15.755
10.755
5.755
0.755
但我只需要最后一个值,例如40.755。我是编码的新手。在这方面,有人可以帮助我如何获得单一价值。
答案 0 :(得分:0)
首先,创建一个列表来保存minutes_values,然后使用builtin max()来获取最大值。
def main():
fmt = '%Y-%m-%d %H:%M:%S'
with open('/home/kamil/Desktop/sensor1/temp.dat', 'rb') as f:
read = f.readlines()[1:]
minutes_values = []
for line in read:
line = line.strip().split(',')
# print line
start_date = line[0] # type is str so i convert it to datetime
start_date = datetime.strptime(start_date, fmt) # type is datetime.datetime and here I need the first timestamp in the file only
current_time = datetime.now()
step_size = 5
differ_time = current_time - start_date
minutes_values.append( differ_time.total_seconds() / 60 )
missed = int(minutes_values / step_size)
expected = .........
missing_data(expected, missed)
print 'minutes_values:::::::::::::::::::', max(minutes_values)
答案 1 :(得分:0)
我也是初学者,但在我看来,for循环是不必要的。看起来你只想要循环返回的第一个值(40.755)并且每个连续的值减少五个,这与你的步长= 5有关?如果更改step_size,请按连续时间更改该数量吗?
如果for循环对于其他东西是必要的,则将代码的两个部分分开:一个用于计算时间差异,一个用于执行for循环正在执行的操作。