ValueError:时间数据“{0}”与格式'%d /%m /%Y'不匹配

时间:2017-10-06 13:31:39

标签: python csv mysql-python

我正在尝试从CSV文件插入MySQL,文件中的第一个“列”是这种格式的日期:

    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)

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

这是我的代码:

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

我的python脚本出现以下错误:

f.fields_for :check_results do |result|

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分:0)

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