【问题标题】:ValueError: time data '{0}' does not match format '%d/%m/%Y'ValueError:时间数据“{0}”与格式“%d/%m/%Y”不匹配
【发布时间】:2018-03-18 07:57:18
【问题描述】:

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

    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'

【问题讨论】:

  • 好的。首先,这似乎与 MySQL 无关,因为datetime.datetime.strptime('{0}', '%d/%m/%Y') 给出了警告。
  • 你应该格式化字符串,即'{0}'.format(your_date_string)。

标签: python csv mysql-python


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您应该在查询执行期间执行日期格式化逻辑。您不能只将逻辑放在插入查询字符串中并期望它起作用(如您所见,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))
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 1970-01-01
      相关资源
      最近更新 更多