2017-10-06 121 views
0

我试图从CSV文件插入MySQL,文件中的第一个'列'是日期这种格式:ValueError:时间数据'{0}'与格式'%d /%m /%Y'不匹配

31/08/2017; 

然后我在表列设置为YYYY-MM-DD

这是我的代码:

import datetime 
    import csv 
    import MySQLdb 
    ... 
    insertionSQL="INSERT INTO transactions (trans_date, trans_desc, trans_amnt) VALUES(" + datetime.datetime.strptime('{0}', '%d/%m/%Y').strftime('%Y-%m-%d') + ",{2},{3}), row)" 
    cur.execute(insertionSQL) 

我从我的Python脚本收到以下错误:

(data_string, format)) 
    ValueError: time data '{0}' does not match format '%d/%m/%Y' 
+0

好的。首先,这似乎与MySQL无关,因为'datetime.datetime.strptime('{0}','%d /%m /%Y')给出了这个警告。 – sam

+0

您应格式化字符串,即“{0}”格式(your_date_string)。 – temasso

回答

0

您应该在查询执行过程中执行日期格式化逻辑。你不能只将逻辑放入插入查询字符串中,并期望它能正常工作(正如你所看到的,strptime试图将字符串{0}根据日期格式字符串转换成日期对象,这显然不能工作!)

insertionSQL = "INSERT INTO transactions (trans_date, trans_desc, trans_amnt) VALUES(%s, %s, %s)" 
    ... # read csv 
    # Reformat the date on the actual data from the CSV! 
    csv_date = datetime.datetime.strptime(csv_date, '%d/%m/%Y').strftime('%Y-%m-%d') 
    # Now all of your input data is formatted correctly, execute the prepared statement. 
    cursor.execute(insertionSQL, (csv_date, csv_desc, csv_amnt)) 
0

我发现了这个问题。我缺少分隔符=“;”所以csv阅读器将整行作为一个值

相关问题