Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a CSV to MySQL with different date format

Tags:

I'm doing my first CSV import into MySQL and noticed that the date in the CSV has the format 31-Jan-2011. How can I convert this to 2011-01-31 so I can place it in the DATE datatype? The first thing which came to mind is let PHP do the conversion then insert it into a 2nd table but I'm guessing that's...not right.

like image 561
enchance Avatar asked Nov 17 '11 06:11

enchance


People also ask

How do I insert date in YYYY-MM-DD format in MySQL?

MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.

Can we change date format in MySQL?

Change the curdate() (current date) format in MySQL The current date format is 'YYYY-mm-dd'. To change current date format, you can use date_format().


2 Answers

You can replace format during importing data from the CSV file, for example -

LOAD DATA INFILE 'file_name.csv' INTO TABLE table_name FIELDS TERMINATED BY ';' LINES TERMINATED BY '\n' (id, column2, column3, @date_time_variable) -- read one of the field to variable SET date_time_column = STR_TO_DATE(@date_time_variable, '%d-%b-%Y'); -- format this date-time variable 

It will format the string like '31-Jan-2011' to a correct DATETIME data type.

More information here - LOAD DATA INFILE Syntax.

like image 149
Devart Avatar answered Sep 30 '22 20:09

Devart


mysql> SELECT DATE_FORMAT('2009-10-04 22:23:00', '%Y-%m-%d'); +------------------------------------------------+ | DATE_FORMAT('2009-10-04 22:23:00', '%Y-%m-%d') | +------------------------------------------------+ | 2009-10-04                                     |  +------------------------------------------------+ 1 row in set (0.00 sec) 
like image 21
Rush Avatar answered Sep 30 '22 20:09

Rush