繁体   English   中英

从python中的csv文件的当前日期时间中减去日期时间

[英]Subtract date time from current datetime of csv file in python

我正在尝试计算从创建和更新文件到当前时刻的时间差(以分钟为单位),以计算丢失数据的数量。 但是我无法正确减去它们。 我的代码如下。

文件中的数据如下所示:

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。 我是编码新手。 有人可以在这方面帮助我如何获得一个单一的价值。

首先,创建一个列表来保存minutes_values,然后使用内置的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)

我也是一个初学者,但是在我看来,for循环是不必要的。 看来您只希望循环返回第一个值(40.755),并且每个连续值都减少5,这与步长= 5有关? 如果更改step_size,连续时间是否会改变该数量?

如果for循环对于其他事情是必需的,则将代码的两部分分开:一个计算出时间差,另一个执行for循环正在做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM