且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MySQL中将日期/时间字符串转换为Unix时间戳

更新时间:2023-02-03 08:50:50

UNIX_TIMESTAMP()函数需要有效的日期/时间格式才能正确转换,因此您需要将现有的日期/时间格式转换为有效/可识别的格式(包括年份)第一.您可以使用MySQL的STR_TO_DATE()函数执行此操作,告诉它您要传入的格式,并以硬编码的年份值进行连接,因为在您的情况下始终为2016.

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')

然后,您可以使用UNIX_TIMESTAMP()函数将该有效日期转换为您的unix时间戳,并在一个步骤中更新所有这些记录:

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'));