python - 时间数据“无”与格式“%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:%”不匹配。谁能帮我?
解决方案
您要做的是解析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)
要处理此错误,您可以检查是否s
像not 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
但即便如此,您的图表也会出错,因为您在列x1
和x2
. 但我认为这就是你能做的或正确获取数据的全部。
或者您可以检查这些列中是否包含行并None
放入循环中并完全跳过该行,例如 -continue
for
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]))
您将跳过刻度,但您将能够绘制图表
推荐阅读
- mysql - 返回多条记录,但每个类似条件应限制 1 条记录
- python - 在python中读取类似结构的pdf表格(不是精确的表格)并将其提取为任何文件格式
- java - Wildfly 18 JMS 执行导致“远程连接突然关闭”
- python - python selenium定位元素问题
- c++ - 如何在 C++ 中使用移动语义进行运算符重载?(优雅地)
- java - 如何使用 Firebase 数据库中的数据在 RecyclerView 上实现加载更多分页(无限滚动)
- c++ - C++ 表示回文
- basic - #define, #macro, #error 拒绝运行
- javascript - 如何在 Javascript 中清除超时后取消 setTimeout() 中的事件
- java - LWJGL 在 glDrawElements 上崩溃