mysql how to convert varchar(10) to TIMESTAMP?

拜拜、爱过 提交于 2020-01-04 16:53:07

问题


I have stored all the date into my database as varchar(10), now I want to converse them into TIMESTAMP.

When I run sql

ALTER TABLE  `demo3` CHANGE  `date`  `date` TIMESTAMP NOT NULL

it alert:

#1292 - Incorrect datetime value: '1320534000' for column 'date' at row 1 

BTW, All my date formart are 10 digital number.


回答1:


You should first change the timestamp to datetime and then can change the type of column.

ALTER TABLE `demo3` MODIFY COLUMN `date` varchar(25);

UPDATE `demo3` SET `date`= FROM_UNIXTIME(`date`);

ALTER TABLE  `demo3` CHANGE  `date`  `date` TIMESTAMP NOT NULL



回答2:


You need to add a new column with the type you want, then update the table, converting the string to number for each row in an update statement.

So Add your new timestamp column with a default of NULL

Then run something similar to:

UPDATE demo3 SET new_timestamp = CONVERT(date, signed)

(You may need to try converting from unix timestamp and back again - see http://kitt.hodsden.org/mysql/converting_to_mysqls_timestamp_from_int11)

Which should push the integers into the timestamp column.

Then get rid of the original date column and rename the timestamp column.




回答3:


First you have to convert that unix timestamp format with the FROM_UNIXTIME function.



来源:https://stackoverflow.com/questions/8356128/mysql-how-to-convert-varchar10-to-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!