1

我编写了一个 Python 脚本,它基本上删除了.csv从 EXCEL 生成的文件(实际上是 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()
4

0 回答 0