【发布时间】:2017-06-04 03:34:37
【问题描述】:
我收到了这个错误
ValueError: time data '140120 1520' does not match format '%Y-%m-%d %H:%M:%S'
我有一个 csv 文件,我必须将它存储在 db 中。 csv文件中的数据看起来
# date day time rec_no tem X Z G
140120 20 1520 920 0.00 0.0 51 0.00
140120 20 1521 921 37.73 46 -596.05 1.21
140120 20 1522 922 31.11 42 31.4000 0.50
140120 20 1523 923 0.00 0.0 -451.50 0.00
140120 20 1524 924 0.00 0.0 -31.500 0.00
我的问题是我必须将第一列(日期)和第三列(时间)结合起来,并根据纪元时间将其转换为时间戳,然后再存储到 MySQL 数据库中。 来自传感器的日期格式,我们在 csv 文件中得到的是
140120
14 represent 2014, 01 represent the month (January) and 20 represent day.
时间到了
1520
15 represent hour and 20 represent minute. and nothing for seconds
so we can append 00 for seconds.
其中天列包含与日期最后 2 位相同的信息,所以我忽略了这一列(天)。 所以为了转换成时间戳,我需要结合日期和时间列。我这样做了,然后重建列表,如我的代码所示。
我在网上搜索并找到了转换日期和时间格式的不同技术,但没有符合我需要的命令或解决方案。 我获取上述 csv 文件数据并转换时间戳的代码如下。
with open(item[1]) as f:
lines = f.readlines()
for k, line in enumerate(lines):
if k >= (int(skip_header_line) + int(index_line_number)):
data_tmp = line.split()
print data_tmp # i got ['140120', '20', '1520', '920', '0.00', '0.0', '51', '0.00', '0', '0.00', '0', '0.00']
newcolumn = data_tmp[0] + ' ' + data_tmp[2]
data = [newcolumn] + data_tmp[3:] # re-build the list so we get
['140120 1520', '920', '0.00', '0.0', '-31.50', '0.00', '0', '0.00', '0', '0.00']
strDate = data[0].replace("\"", "")
print strDate # i got here 140120 1520
timestamp = datetime.datetime.strptime(strDate,
'%Y-%m-%d %H:%M:%S')
ts = calendar.timegm(timestamp.timetuple())
data_buffer = []
for val in data_tmp:
if val == " ":
val = None
data_buffer.append(val)
else:
data_buffer.append(float(val))
cursor.execute(add_data, data_buffer)
cnx.commit()
cursor.close()
cnx.close()
如果有人给我一个将“140120 1520”转换为时间戳的提示或示例,我将非常感激,因为我不知道如何处理这个问题。谢谢
【问题讨论】: