首页 > 解决方案 > 时间数据“无”与格式“%H:%M:%S”不匹配

问题描述

在这里,我有时间值,我使用 python 来绘制从 Excel.csv 文件导入的图形。在这里,我有一些没有的行。当我对其进行编码时,显示时间数据 none 与 '%H:%M:%S' 不匹配的错误。在这里,我将时间与值表包括在内。

x 数据 y 数据 x1 数据 y1 数据 x2 数据 y2 数据
0:06:15 141 0:08:00 131 0:06:45 136
0:09:25 95 0:08:15 117 0:09:30 95
0: 11:00 149 0:08:30 109 0:11:30 139
0:13:50 85 0:08:45 103 0:13:30 95
0:16:25 135 0:09:00 97 0:15: 25 105
0:19:00 63 无 无 0:18:00 97
0:20:00 111 无 无 0:19:30 100
0:22:05 115 无 无 0:22:15 115
0:23:40 287无 无 无 无

我的代码是,

condition = ""
weight = ""
height = ""
date = ""

label1 = ""
label2 = ""
label3 = ""

x  = []
y  = []
x1 = []
y1 = []
x2 = []
y2 = []


def convertTime(s):
	tm = time.strptime(s, "%H:%M:%S")
	return datetime.datetime(date.tm_year,date.tm_mon, date.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec)

with open('data.csv') as csv_file:
  csv_data = csv.reader(csv_file, delimiter=',')
  row_num = 0
  for row in csv_data:
    if(row_num == 0):
      condition = row[0]
      weight = row[1]
      height = row[2]
    elif(row_num == 1):
      date = time.strptime(row[0], "Date:-%Y/%m/%d")
    elif(row_num == 2):
      label1 = row[0]
      label2 = row[1]
      label3 = row[2]
    elif(row_num > 3): #Data starts here
      x.append(convertTime(row[0]))
      y.append(int(row[1]))
      x1.append(convertTime(row[2]))
      y1.append(int(row[3]))
      x2.append(convertTime(row[4]))
      y2.append(int(row[5]))
    row_num = row_num + 1

plt.plot(x,y,label=label1)
plt.stem(x1,y1,'C1-.','C1o',label=label2)
plt.stem(x2,y2,'C2-.','C2o',label=label3)
plt.legend()
plt.gcf().autofmt_xdate()
plt.show()

print(x)
print(y)

我的错误是,

ValueError:时间数据“无”与格式“%H:%M:%”不匹配。谁能帮我?

标签: pythonjupyter-notebook

解决方案


您要做的是解析None到一个datetime对象,但在此之前,您需要告诉 datetime 您的日期格式

在您的代码中 -

def convertTime(s):
    # when s = None, you get that error 
    tm = time.strptime(s, "%H:%M:%S")
    return datetime.datetime(date.tm_year,date.tm_mon, date.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec)

要处理此错误,您可以检查是否snot None-

def convertTime(s):
    if s:
        tm = time.strptime(s, "%H:%M:%S")
        return datetime.datetime(date.tm_year,date.tm_mon, date.tm_mday,
    return None

但即便如此,您的图表也会出错因为您在列x1x2. 但我认为这就是你能做的或正确获取数据的全部。

或者您可以检查这些列中是否包含行并None放入循环中并完全跳过该行,例如 -continuefor

elif(row_num > 3): #Data starts here
    if None in row:
        row_num += 1
        continue # This will make you skip the row
    x.append(convertTime(row[0]))
    y.append(int(row[1]))
    x1.append(convertTime(row[2]))
    y1.append(int(row[3]))
    x2.append(convertTime(row[4]))
    y2.append(int(row[5]))

您将跳过刻度,但您将能够绘制图表


推荐阅读