Search code examples
mysqlsqltimeload-data-infile

mysql infile convert string to time format


I have a TSV that I'm trying to infile into a mySQL table. A couple columns are time formats, but they don't match the standard time format of HH:MM:SS, instead they look like HH:MM AM/PM

I've seen examples to do this with PHP, but I was hoping there was a way to do with with mysql str_to_date

Here's what I've worked up so far.

LOAD DATA LOCAL INFILE 
'C:\\SINGLE_PROP\\open_houses.txt' 
REPLACE INTO TABLE singleprop.jos_openhouse 
IGNORE 1 LINES
SET OHSSTARTTM = STR_TO_DATE('%g:%i %a', '%g:%i:%s');

I keep getting an incorrect time format error. Here's how the table looks.

CREATE TABLE `jos_openhouse` (
  `OHSSTARTDT` DATE NOT NULL,
  `OHSHOSTBID` varchar(14) NOT NULL,
  `OHSMLSNO` int(7) NOT NULL,
  `OHSSTARTTM` TIME NOT NULL,
  `OHSENDTM'` TIME NOT NULL,
  `OHSREMARK` TEXT,
  `OHSTYPE` TEXT,
  `OHSUPDTDT` TIMESTAMP,
PRIMARY KEY (`OHSMLSNO`))
ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

Should the column be created as 'TEXT' first so infile can put the data there and then it's converted to time format after it's been imported?


Solution

  • Try this:

    SELECT STR_TO_DATE('11:15 PM', '%h:%i %p') ;
    

    OUTPUT

    TIME
    --------
    23:15:00
    

    Try this:

    LOAD DATA LOCAL INFILE 
    'C:\\SINGLE_PROP\\open_houses.txt' 
    REPLACE INTO TABLE singleprop.jos_openhouse (col1, col2, ..., @OHSSTARTTM)
    IGNORE 1 LINES
    SET OHSSTARTTM = STR_TO_DATE(@OHSSTARTTM, '%h:%i %p');