mysqlstr-to-date

Incorrect datetime value loading data into MySQL from file with str_to_date function


This is driving me crazy, trying this for 2 days, looking here and in mysql documentation without succes.

I have a file with this data:

Test,String 1,Completed,full,04/20/21 12:10:01,1618913401
Test,String 2,Completed,full,04/20/21 12:15:01,1618913701
Test,String 3,Completed,full,04/20/21 12:30:02,1618914602
Test,String 4,Completed,full,04/20/21 13:30:01,1618918201
Test,String 5,Completed,full,04/20/21 14:00:01,1618920001

And am trying to insert it in mysql with this command:

LOAD DATA LOCAL INFILE 'output2.csv'
INTO TABLE test
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(`Session Type`, `Specification`, `Status`, `Mode`, @StartTime, `Start Time_t`)
SET `Start Time` = STR_TO_DATE(@StartTime, '%d/%m/%y %T');

Result:
Query OK, 5 rows affected, 10 warnings (0.00 sec)
Records: 5  Deleted: 0  Skipped: 0  Warnings: 10

MariaDB [data]> SHOW WARNINGS;
+---------+------+------------------------------------------------------------------------+
| Level   | Code | Message                                                                |
+---------+------+------------------------------------------------------------------------+
| Warning | 1411 | Incorrect datetime value: '04/20/21 12:10:01' for function str_to_date |
| Warning | 1048 | Column 'Start Time' cannot be null                                     |
| Warning | 1411 | Incorrect datetime value: '04/20/21 12:15:01' for function str_to_date |
| Warning | 1048 | Column 'Start Time' cannot be null                                     |
| Warning | 1411 | Incorrect datetime value: '04/20/21 12:30:02' for function str_to_date |
| Warning | 1048 | Column 'Start Time' cannot be null                                     |
| Warning | 1411 | Incorrect datetime value: '04/20/21 13:30:01' for function str_to_date |
| Warning | 1048 | Column 'Start Time' cannot be null                                     |
| Warning | 1411 | Incorrect datetime value: '04/20/21 14:00:01' for function str_to_date |
| Warning | 1048 | Column 'Start Time' cannot be null                                     |
+---------+------+------------------------------------------------------------------------+

Start Time is datetime type.


Solution

  • If you look closely, the date is in the confusing American format, month cannot be a 20 :) So just fix the format as below

    STR_TO_DATE('04/20/21 14:00:01', '%m/%d/%y %T');