![](/img/trans.png)
[英]ValueError: time data does not match format '%Y-%m-%d %H:%M:%S.%f'
[英]ValueError: time data '140120 1520' does not match format '%Y-%m-%d %H:%M:%S'
我得到这个错误
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.
其中“日期”列包含与日期的后两位数字相同的信息,因此我忽略了此列(日期)。 因此,为了转换为时间戳,我需要组合日期和时间列。 我这样做了,然后按照我的代码所示重建了列表。
我在网上搜索,发现了不同的技术来转换日期和时间格式,但是没有命令或解决方案符合我的需要。 我的代码来获取上述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”转换为时间戳,我将非常感激,因为我不知道如何处理此问题。 感谢名单
尝试'%y%m%d %H%M'
。 值得指出的是,您需要使用%y
而不是%Y
来匹配没有世纪的年份,例如2014年的“ 14”。
from datetime import datetime
s = '140120 1520'
print(datetime.strptime(s, '%y%m%d %H%M'))
产量
2014-01-20 15:20:00
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.