1 回答
TA贡献1772条经验 获得超6个赞
您对 timestamp 列中的一个或多个值有疑问,其中一行看起来像440,并且会导致time data '' does not match format '%H:%M:%S'
包裹date = datetime.strptime(row[1], '%H:%M:%S').time()在一个try-except块中。
test.csv
user_id,timestamp
563,0:00:21
671,0:00:26
780,0:00:28
440,
代码
import csv
from datetime import datetime
path = "test.csv"
file = open(path, newline='')
reader = csv.reader(file, delimiter=',')
header = next(reader) # Ignore first row.
data = []
for row in reader:
# row = [user_id, timestamp]
user_id = row[0]
try:
timestamp = datetime.strptime(row[1], '%H:%M:%S').time()
except ValueError as e:
timestamp = row[1]
# continue # use this if you do not want the row added to data, comment it out otherwise
data.append([user_id, timestamp])
print(data)
[out]:
[['563', datetime.time(0, 0, 21)], ['671', datetime.time(0, 0, 26)], ['780', datetime.time(0, 0, 28)], ['440', '']]
添加回答
举报