Skip to content
Advertisement

How to change a column’s datatype from text to datetime in mysql?

I’m trying this but it’s not working. My original data is formatted like this month/date/year (eg: 2/24/20)

UPDATE Packages SET `date` = STR_TO_DATE(`date`, '%Y-%m-%d %T'); 
ALTER TABLE Packages MODIFY COLUMN `date` DATETIME;

Advertisement

Answer

You should create a new datetime column and populate it using STR_TO_DATE with the text date:

ALTER TABLE Packages ADD COLUMN new_date DATETIME;
UPDATE Packages SET new_date = STR_TO_DATE(date, '%Y-%m-%d %T');

If you’d like, you may also drop the original date column, and then rename the new column:

ALTER TABLE Packages DROP COLUMN date;
ALTER TABLE Packages RENAME COLUMN new_date TO date;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement