我编写了一个Python脚本,它基本上删除了从EXCEL生成的.csv
文件(实际上是OpenOffice变体,但它基本上是相同的。)
.csv
包括灯光的时间。一组数据包含灯,另一组包含灯。我正在尝试创建一个脚本,它需要两次,转换它们,然后吐出一个减法问题,告诉我灯光的总小时数。
踢球者有时在0800打开灯,然后在第二天早晨0100关灯。我的脚本在第一次在我的数据集中发生之前完成所有处理,然后在遇到障碍时立即退出。
第二个问题:我设置代码的方式,日期时间数字中的前三个数字被%j
分配给一年中的某一天。当我有超过365个值时,这会打破吗?还有什么选择?
我得到的错误:
Traceback (most recent call last):
File "D:\Documents\Programming\Python scripts\Actually useful\excel_strip.py", line 55, in <module>
print(datetime.strptime(offlst[idx], '%j%H%M'))
File "C:\Python27\lib\_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 8
以下是相关代码。旁边带有注释的行是相关部分。
import csv
from datetime import datetime
inc = 0
inc2 = 0
inc3 = 0
inc4 = 0
inc5 = 1
inc6 = 1
inc7 = 0
datelst = []
templst = []
onlst = []
offlst = []
time_diff = []
waterlst = []
path = raw_input("Enter the pathname for your .csv file. (e.g. C:\Myfolder\myfile.csv: ")
out = open(path, 'rb')
data = csv.reader(out)
data = [row for row in data]
for row in data:
if row[inc].startswith('DATE'):
loadlist = row[inc + 1]
datestr = loadlist[:10]
datelst.append(datestr)
elif row[inc2].startswith('TEMP'):
tempstr = row[inc2 + 1]
templst.append(tempstr)
elif row[inc3].startswith('LIGHT ON'): #This block takes the light on times and writes them all to a list with padding for a day value
onstr = row[inc3 + 1]
if onstr != 'N/A':
onlst.append(format(inc5, '03d') + onstr)
inc5+=1
else:
onlst.append(onstr)
inc5+=1
elif row[inc4].startswith('LIGHT OFF'): #Same as above for light off times
offstr = row[inc4 + 1]
if offstr != 'N/A':
offlst.append(format(inc6, '03d') + offstr)
inc6+=1
else:
offlst.append(offstr)
inc6+=1
elif row[inc7].startswith('H2O AMNT (mL)'):
waterstr = row[inc7 + 1]
waterlst.append(waterstr)
for idx, val in enumerate(onlst): #The following block tries to iterate over the list to make times that can be subtracted by one another.
if onlst[idx] != 'N/A':
print(datetime.strptime(onlst[idx], '%j%H%M'))
print(datetime.strptime(offlst[idx], '%j%H%M'))
light_on = datetime.strptime(onlst[idx], '%j%H%M')
light_off = datetime.strptime(offlst[idx], '%j%H%M')
time_diff.append(str(light_off - light_on))
else:
time_diff.append('N/A')
for idx, val in enumerate(time_diff):
if time_diff[idx].startswith('-'):
loadlist2 = time_diff[idx]
timestring = loadlist2[8:]
time_diff[idx] = timestring
out = open('newlog.csv','wb')
output = csv.writer(out)
output.writerow(datelst)
output.writerow(templst)
output.writerow(time_diff)
output.writerow(waterlst)
out.close()