我想将YYYY-MM-DD列转换为unix时间戳。与此问题类似:MySQL - Convert MM/DD/YY to Unix timestamp
MySQL似乎没有将'2012-05-10'的值转换为正确的unixtime。以下是建议的失败函数:
SELECT UNIX_TIMESTAMP(CAST(dateid AS DATE)) AS unixtime
答案 0 :(得分:1)
您使用的MySQL
版本是什么?正如SQLFiddle中的MySQL 5.5.27测试的那样,这两个查询工作
SELECT UNIX_TIMESTAMP(CAST('2012-05-10 00:00:00' AS DATETIME)) As UnixTime;
SELECT UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE)) As UnixTime;
答案 1 :(得分:1)
我不确定你究竟遇到了什么问题,但以下工作正常:
CREATE TABLE ex (dt VARCHAR(20));
INSERT INTO ex SET dt = '2012-05-10';
SELECT
UNIX_TIMESTAMP('2012-05-10') ex1,
UNIX_TIMESTAMP(dt) ex2,
UNIX_TIMESTAMP(CAST('2012-05-10' AS DATE)) ex3,
UNIX_TIMESTAMP(CAST(dt AS DATE)) ex4
FROM ex;
返回:
+------------+------------+------------+------------+
| ex1 | ex2 | ex3 | ex4 |
+------------+------------+------------+------------+
| 1336633200 | 1336633200 | 1336633200 | 1336633200 |
+------------+------------+------------+------------+
如您所见,如果字符串的格式为CAST()
或YYYY-MM-DD
,则无需YYYY-MM-DD HH:MM:SS
,因为MySQL会将此格式的字符串隐式转换为{{1} }第