Home > Database > Mysql Tutorial > body text

How to Import CSV Dates with Alternate Formats into MySQL?

Susan Sarandon
Release: 2024-11-22 13:33:12
Original
922 people have browsed it

How to Import CSV Dates with Alternate Formats into MySQL?

Importing a CSV to MySQL with Alternate Date Format

Importing a CSV file into MySQL can introduce challenges when the date formats differ between the CSV and the database. Encountering dates in the format 31-Jan-2011, it's necessary to convert them to the compatible format 2011-01-31 to store them in a DATE datatype.

Fortunately, MySQL provides a straightforward method to handle this conversion during the import process. Utilizing the LOAD DATA INFILE command, you can specify a date format transformation rule as follows:

LOAD DATA INFILE 'file_name.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\n'
(id, column2, column3, @date_time_variable) -- read one of the field to variable
SET date_time_column = STR_TO_DATE(@date_time_variable, '%d-%b-%Y'); -- format this date-time variable
Copy after login

By incorporating the STR_TO_DATE() function, you can convert the date string using the provided format (%d-%b-%Y in this case) into a MySQL-compatible DATETIME format. The resulting data will be correctly stored in the specified date_time_column.

Refer to the LOAD DATA INFILE Syntax documentation for further information on utilizing this technique for CSV imports.

The above is the detailed content of How to Import CSV Dates with Alternate Formats into MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template