joe
joe

Reputation: 31

when I am inserting datetime into mysql from csv file using python I am getting error

I am inserting datetime into mysql from csv am getting following error.

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

my datetime is like this "8/10/2017 12:59"

And my code is as follows

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"

Upvotes: 0

Views: 1381

Answers (1)

James Scott
James Scott

Reputation: 1082

Instead of using SQL could you reformat the date in the native python code? See an example below (note this is indicative only).

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"

Let me know if you want me to code this up and test it, or have any other issues.

Here's some updated code (changes yours a bit for expedience) this uploads this data:

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

To this table:

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

Like this:

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"

With these results:

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)

Regards,

James

Upvotes: 1

Related Questions