日期时间不能手动

2024-06-24 13:14:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个Python脚本,基本上剥离了从EXCEL生成的.csv文件(实际上是OpenOffice变体,但基本上是一样的)。你知道吗

.csv包括灯光的计时。一组数据包含light on,另一组包含light off。我试着做一个脚本,把这两个时间都转换,然后吐出一个减法问题,告诉我灯亮的总小时数。你知道吗

关键在于,有时8点开灯,第二天早上1点又关灯。我的脚本在数据集中第一次发生这种情况之前,所有的处理都做得很好,一旦遇到问题就退出。你知道吗

第二个问题:按照我设置代码的方式,日期时间编号中的前三个数字由%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()

Tags: csvinfordatadatetimetimediffrow