从Python中的.csv中减去时间

elif row[inc3].startswith('LIGHT ON'): onstr = row[inc3 + 1] onlst.append(onstr) elif row[inc4].startswith('LIGHT OFF'): offstr = row[inc4 + 1] offlst.append(offstr) for idx, val in enumerate(onlst): tdifflst.append(float(offlst[idx]) - float(onlst[idx])) 

在这里,我从脚本中提取代码,从EXCEL电子表格中提取数据并对其进行分析。 这两种types的值是一个灯打开的时间和一个灯熄灭的时间。 例如在0500点亮,在2300点亮。

我想从closures时间减去按时,但我显然不能把这些作为真正的花车,因为60分钟到一小时的事情。 我如何对待这些“浮动”像他们的时代?

你可以做这样的事情:

 >>> from datetime import datetime >>> light_on = datetime.strptime('0500', '%H%M') >>> light_off = datetime.strptime('2300', '%H%M') >>> print light_off - light_on 18:00:00 

light_onlight_off是date时间对象,不同的是timedelta对象。

我认为你至less暗示时间总是以hhmm的forms报告

因此修改你的代码是微不足道的

 elif row[inc3].startswith('LIGHT ON'): raw_time = row[inc3 + 1] hour = raw_time[0:2] minute = raw_time[2:] minute_hour_fraction = int(minute)/60. str_time = ''.join([hour,str(minute_hour_fraction)[1:]]) float_time = float(str_time) onlst.append(float_time) elif row[inc4].startswith('LIGHT OFF'): same as above 

其他方式:

 import datetime hh, mm = int(offstr[0:2]), int(offstr[2:4]) # a dummy date 101/1/1 toff = datetime.datetime(101, 1, 1, hh, mm) hh, mm = int(onstr[0:2]), int(onstr[2:4]) tdiff = toff - datetime.timedelta(hours=hh, minutes=mm) tdiff.hour tdiff.minute 

您也可以将整个date(年,月,日)添加到date时间对象中,以便您可以获得大于24小时的差异结果。