Converting date/time string to unix timestamp in MySQL

荒凉一梦 提交于 2020-01-13 07:28:07

问题


We have a database with all the dates and times stored in one column called timestamp. The format of the date/time in the column "timestamp" is as: 03 Aug 08:10am.

I would like to convert this (03 Aug 08:10am) to UNIX TIMESTAMP in MySQL and not PHP because we already have over 500 rows with this format: 03 Aug 08:10am.

I tried create a new INT column called new_timestamp and ran this query:

UPDATE table_name SET new_timestamp = UNIX_TIMESTAMP(timestamp);

However, it shows that 0 rows were affected.

This is not a duplicate, don't redirect me to how to convert in PHP. Read the question first :)


回答1:


The UNIX_TIMESTAMP() function requires a valid date/time format to convert correctly, so you need to convert your existing date/time format to a valid/recognised format (including the year) first. You can do this using MySQL's STR_TO_DATE() function, telling it what format you are passing in, and concatenating in a hard-coded year value as it's always 2016 in your case.

STR_TO_DATE(CONCAT('2016-', <your date/time value>), '%Y-%d %b %h:%i%p')

You can then use the UNIX_TIMESTAMP() function to convert that valid date to your unix timestamp and update all those records in a single step:

UPDATE table_name
   SET new_timestamp = 
       UNIX_TIMESTAMP(STR_TO_DATE(CONCAT('2016-', timestamp), '%Y-%d %b %h:%i%p'));


来源:https://stackoverflow.com/questions/38896445/converting-date-time-string-to-unix-timestamp-in-mysql

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