简体   繁体   中英

Date Time Conversion in MySQL

I imported a CSV file into MySQL. The CSV file contains Date/Time in the format 'mm/dd/yyyy hh:mm' .

It gets imported into MySQL only as text. So I did import it as text. I then created another field hoping to convert this text value to date time in this format 'mm-dd-yyyy hh:mm' OR in this format 'YYYY-mm-dd hh:mm' . But it does not work. Below is my code.

ALTER TABLE table1 ADD COLUMN StartDateNEW DATETIME;
SET SQL_SAFE_UPDATES = 0;
UPDATE table1 SET StartDateNEW = STR_TO_DATE(StartDate, '%m/%e/Y %H:%i');
SET SQL_SAFE_UPDATES = 1;

Sample Data:

在此处输入图片说明

Some more sample data:

在此处输入图片说明

I have been trying this for over an hour now. Can someone please help?

If you are loading data using the LOAD DATA INFILE syntax , it should be possible to handle conversion on the fly.

Assuming that your source csv file looks like:

StartDate, EndDate, Value
"1/10/2012 10:05", "1/11/2012 11:51", abc
"1/13/2012 08:00", "1/15/2012 09:01", abc

You can defined columns StartDate and EndDate as datetime datatype, and simply do:

LOAD DATA INFILE '/path/to/my/file.csv' INTO TABLE mytable
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\r\n' -- or '\n'
    IGNORE 1 LINES
    (@StartDate, @EndDate, Value)
    SET 
        StartDate = STR_TO_DATE(@StartDate, '%c/%e/%Y %k:%i'),
        EndDate =   STR_TO_DATE(@EndDate,   '%c/%e/%Y %k:%i')
;

NB: and if you are curently not using LOAD DATA INFILE ... I would still recommend migrating your code to use it. This is the proper way to do this in MySQL, it works on all clients.... and it is very fast (see this link ).

Based on your sample data, the correct format string for STR_TO_DATE is

%c/%e/%Y %k:%i
  • %c allows for single digit month numbers
  • %e allows for single digit day numbers
  • %Y four digit year
  • %k allows for single digit hours
  • %i two digit minutes

All the format strings are described in the manual for DATE_FORMAT .

Demo on dbfiddle

A quick hack is as follows:

  1. Open CSV File in Excel
  2. Select the date column
  3. Change date format to yyyy-mm-dd using cell format popup
  4. Save file
  5. Import to MySQL

This was you don't need to import in text form and then try to convert the data into DateTime .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM