当我使用python从csv文件将datetime插入mysql时,我收到错误

时间:2017-08-23 05:22:57

标签: python mysql

我正在从csv中将datetime插入到mysql中,导致以下错误。

_mysql_exceptions.OperationalError: (1292, "Incorrect datetime value: '8/13/2017 19:10' for column 'js_signup' at row 1").

我的约会时间就像这样“8/10/2017 12:59”

我的代码如下

import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',user='root',passwd='Yogi123$',db='wisdom_india')
 cursor = mydb.cursor()
csv_data = csv.reader(file('test_csv.csv'))
for row in csv_data:
    cursor.execute("""INSERT INTO testcsv(js_id,
    js_name,js_email,js_signup)
    VALUES(%s,%s,%s,STR_TO_DATE(%s,'%%%m/%%%d/%%%Y %%%h:%%%i'))""", row)
mydb.commit()
cursor.close()
print "Done"

1 个答案:

答案 0 :(得分:0)

您可以在本机python代码中重新格式化日期而不是使用SQL吗?请参阅下面的示例(请注意,这仅供参考)。

import csv
import MySQLdb
mydb = MySQLdb.connect(host='localhost',user='root',passwd='Yogi123$',db='wisdom_india')
 cursor = mydb.cursor()
csv_data = csv.reader(file('test_csv.csv'))
for row in csv_data:
    cursor.execute("""INSERT INTO testcsv(js_id,
    js_name,js_email,js_signup)
    VALUES(%s,%s,%s," + datetime.datetime.strptime(%s, '%m-%d-%Y %h:%m').strftime('%Y-%m-%d %h:%m') + ")""", row)
mydb.commit()
cursor.close()
print "Done"

如果您希望我对其进行编码并对其进行测试,或者有任何其他问题,请告诉我。

这里有一些更新后的代码(为了方便起见而改变一下),这会上传这些数据:

1,2,3,01-13-2017 13:00
1,2,3,01-13-2017 13:00
1,2,3,01-13-2017 13:00

到此表:

CREATE TABLE testLoad(js_id INT UNSIGNED, js_name INT UNSIGNED, js_email INT UNSIGNED, js_signup DATETIME);

像这样:

import csv
import MySQLdb
import datetime
mydb = MySQLdb.connect(host='localhost',user='root',passwd='',db='test')
cursor = mydb.cursor()
with open('test_csv.csv', 'r') as csvfile:
    csv_data = csv.reader(csvfile)
    for row in csv_data:
        VInsert = "INSERT INTO testLoad(js_id, js_name,js_email,js_signup) VALUES(" + row[0] + ", " + row[1] + ", " + row[2] + ", '" + datetime.datetime.strptime(row[3], '%m-%d-%Y %H:%M').strftime('%Y-%m-%d %H:%M') + "')"
        cursor.execute(VInsert)
mydb.commit()
cursor.close()
print "Done"

有了这些结果:

SELECT * FROM testLoad;
+-------+---------+----------+---------------------+
| js_id | js_name | js_email | js_signup           |
+-------+---------+----------+---------------------+
|     1 |       2 |        3 | 2017-01-13 13:00:00 |
|     1 |       2 |        3 | 2017-01-13 13:00:00 |
|     1 |       2 |        3 | 2017-01-13 13:00:00 |
+-------+---------+----------+---------------------+
3 rows in set (0.00 sec)

此致

詹姆斯