这对于 MySQL 的日期和时间函数来说并不是很困难。STR_TO_DATE执行导入所需的操作:
我收到数据的格式是 mm/dd/yy hh:mm AM/PM 或 null。
你得到你的 DATETIME 值
STR_TO_DATE(yourValue, '%m/%d/%y %h:%i %p')
您可以在函数DATE_FORMAT的描述中找到 STR_TO_DATE 的说明符
对于导出,您可以使用已经提到的函数 DATE_FORMAT 进行反向操作,并使用完全相同的格式字符串:
SELECT DATE_FORMAT(your_datetime_col, '%m/%d/%y %h:%i %p')
看看这个演示
您可以像这样在 INSERT 语句中进行转换:
INSERT INTO example (date_time) VALUES
(STR_TO_DATE('09/26/14 07:30 AM', '%m/%d/%y %h:%i %p'));
看到它在更新的演示中工作
使用 LOAD DATA INFILE 自定义导入
让我们有一个example
有两列的表,id
并且date_time
作为
CREATE TABLE example (
id INT NOT NULL PRIMARY KEY,
date_time DATETIME
);
我们还有一个 CSV 文件 example.csv,其中包含如下数据:
id,date
1,09/26/14 07:30 AM
2,07/23/14 07:30 PM
要使用 LOAD DATA INFILE 导入此文件,您将使用以下语句:
LOAD DATA INFILE 'path/on/server/to/example.csv'
INTO TABLE example
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES -- because of the column headers in the first line
(id, @var1) -- You've got to map every field of your csv file to a column
-- of your table.
-- You've got to list the names of the columns of your table,
-- not the headers in the csv file.
-- if one field should be ignored, use another variable for this
-- field.
SET date_time = STR_TO_DATE(@var1, '%m/%d/%y %h:%i %p');
如果 csv 文件中的日期包含指示 NULL 值的文字字符串“null”,则使用 CASE 运算符:
date
09/26/14 07:30 AM
null
07/23/14 07:30 PM
那么我们必须使用
LOAD DATA INFILE 'path/on/server/to/example.csv'
INTO TABLE example
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n' -- your line endings
IGNORE 1 LINES -- because of the column headers in the first line
(@var1) -- read all parts of the date in variables
SET completionTime = CASE
WHEN @var1 = 'null' THEN NULL
ELSE STR_TO_DATE(@var1, '%m/%d/%y %h:%i %p')
END;
包含分隔符的字段的问题,在这种情况下是逗号,您已经通过用封闭字符封闭这些字段(或简单地全部)来解决。
但我们真的应该看看你的真实格式。