10
votes

I've imported a CSV file into mysql with dates in format dd/mm/yyyy.

I now need a query to convert it from text to date format yyy-mm-dd.

4

4 Answers

17
votes

You could use the STR_TO_DATE(str, format) MySQL function.

Example switching out my_date_col for a converted one:

BEGIN;
 ALTER TABLE `date_test` 
  ADD COLUMN `my_date_col_converted` DATE;

 UPDATE `date_test` 
  SET `my_date_col_converted` = STR_TO_DATE(`my_date_col`, '%d/%c/%Y');

 ALTER TABLE `date_test` 
  DROP COLUMN `my_date_col`;

 ALTER TABLE `date_test` 
  CHANGE COLUMN `my_date_col_converted` `my_date_col` DATE;
COMMIT;
4
votes

You can use STR_TO_DATE() in the following way to convert your text in to a DATE:

STR_TO_DATE( datefield , "%d/%m/%Y" )

If you need this DATE in a specific format, you can use DATE_FORMAT().
This probably isn't necessary in your case, but here's an example for completeness:

DATE_FORMAT( STR_TO_DATE( datefield , "%d/%m/%Y" ) , "%Y/%m/%d" )

So, you could do this over the whole table with a single UPDATE to replace the current data with the reformatted data (while keeping the datatype the same):

UPDATE tableName
SET originalDate = DATE_FORMAT(STR_TO_DATE(originalDate,"%d/%m/%Y" ),"%Y/%m/%d" );

Or, if you want to convert the datatype of the column DATE you could alter the table to create a new DATE formatted column, use the above update to fill that column, remove the original column, and then (optionally) rename the new column to the old name.

ALTER tableName
ADD modifiedDate DATE;

UPDATE tableName
SET modifiedDate = DATE_FORMAT( STR_TO_DATE( originalDate ,"%d/%m/%Y" ) ,"%Y/%m/%d" );

ALTER tableName
DROP COLUMN originalDate; 

ALTER tableName
CHANGE COLUMN modifiedDate originalDate;
1
votes

This should work but it doesn't:

BEGIN;
 ALTER TABLE `date_test` 
  ADD COLUMN `my_date_col_converted` DATE;
 UPDATE `date_test` 
  SET `my_date_col_converted` = STR_TO_DATE(`my_date_col`, '%d/%c/%Y');
 ALTER TABLE `date_test` 
  DROP COLUMN `my_date_col`;
 ALTER TABLE `date_test` 
  CHANGE COLUMN `my_date_col_converted` `my_date_col` DATE;
COMMIT;

Also this should work: Doesn't Work

UPDATE db_test SET anticipated_court_date = DATE_FORMAT(STR_TO_DATE(anticipated_court_date,"%d/%m/%Y" ),"%Y-%m-%d" );

Server version: 5.0.95-community-log MySQL Community Edition (GPL)

However this works:

SELECT STR_TO_DATE('8/31/12', '%m/%d/%Y'); // WORKS

Using MySQL - I couldn't find any solution that worked reliably. Even the same exact date wasn't converted successfully.

The solution I've found is this:  PHP
$user_date = "8/31/12"; // WORKS
$mysql_date = date('Y-m-d H:i:s', strtotime($user_date));
0
votes

The above were helpful, but the following worked for me on Mysql.

ALTER TABLE `tablename` ADD `newcolumn` DATE NOT NULL ;
UPDATE `tablename` SET `newcolumn`=STR_TO_DATE(`oldcolumn`, '%d/%c/%Y')

Now delete the oldcolumn (if you wish).