mysql infile convert string to time format

Plummer picture Plummer · Jan 16, 2013 · Viewed 27.3k times · Source

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?

Answer

Saharsh Shah picture Saharsh Shah · Jan 16, 2013

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');