Date imported from csv into mysql as 0000-00-00

If it didn't work, just add columns to your CVS for year, month and day and separate day, month and year of your date, and use the following:

set date_column = concat(@year , '-' , @month , '-' , @day)


Please have a try with this one:

LOAD DATA LOCAL INFILE '/path/to/csv/file.csv' 
INTO TABLE mytable 
LINES TERMINATED BY '\n'
(id, task, hoursWorked, @var1, @var2) 
SET begindate = STR_TO_DATE(@var1, '%m/%d/%Y'),     
enddate = STR_TO_DATE(@var2, '%m/%d/%Y');

For more info see LOAD DATA and STR_TO_DATE

Note: I deleted the FIELDS TERMINATED BY ',' ENCLOSED BY '"' part, cause I neither see , nor " in your CSV. But if it works fine for you the way it is, feel free to revert :)


The default date format is YYYY-MM-DD:

mysql> SELECT @@date_format;
+---------------+
| @@date_format |
+---------------+
| %Y-%m-%d      |
+---------------+

... thus MySQL won't recognise stuff like 11/17/2012 as a proper date. In theory, you should be able to change the default format, but I'm not sure it can be done in session scope and I wouldn't recommend to change it for the whole server. It's better to make the transformation yourself. The trick is to insert the value into a variable rather than a column.

Additionally, there're two other issues:

  • Your CSV file contains a header line.
  • Your fields are not separated by ,.

Assuming your file uses tabs as separators, the complete command would be:

LOAD DATA LOCAL INFILE '/path/to/csv/file.csv'
INTO TABLE mytable
FIELDS TERMINATED BY '\t' ENCLOSED BY '"' LINES TERMINATED BY '\n'
IGNORE 1 LINES
(id, task, hoursWorked, @tmp_begindate, @tmp_enddate)
SET begindate = STR_TO_DATE(@tmp_begindate, '%m/%d/%Y'),
    enddate = STR_TO_DATE(@tmp_enddate, '%m/%d/%Y');

MySQL doesn't actually allow to change @@date_format anyway:

mysql> SET @@date_format='%d/%m/%Y';
ERROR 1238 (HY000): Variable 'date_format' is a read only variable

As the MySQL 5.6 manual explains:

This variable is unused. It is deprecated as of MySQL 5.6.7 and will be removed in a future MySQL release.

Also, at Date and Time Types we can read:

MySQL retrieves values for a given date or time type in a standard output format, but it attempts to interpret a variety of formats for input values that you supply (for example, when you specify a value to be assigned to or compared to a date or time type). For a description of the permitted formats for date and time types, see Section 10.1.3, “Date and Time Literals”. It is expected that you supply valid values. Unpredictable results may occur if you use values in other formats.

Although MySQL tries to interpret values in several formats, date parts must always be given in year-month-day order (for example, '98-09-04'), rather than in the month-day-year or day-month-year orders commonly used elsewhere (for example, '09-04-98', '04-09-98').

Tags:

Mysql

Csv

Import