如何在mysql中将DATETIME转换为TIMESTAMP?

时间:2016-06-17 12:25:16

标签: mysql datetime unix-timestamp

我的表中有DATETIME列,具有2015-04-23 11:17:49属性 尝试将其转换为unix时间戳,根据我需要的mysql文档,只需将该字段放入UNIX_TIMESTAMP()函数中,我将得到 - > 1223423442 - 时间戳,但它不起作用,我只有00:00:00 尝试了很多东西:

// doesn't work
UNIX_TIMESTAMP(CAST(`updated` AS CHAR(100))) AS updated_at,
// doesn't work
UNIX_TIMESTAMP(`updated`) AS updated_at,
//doesn't work
UNIX_TIMESTAMP(STR_TO_DATE(CAST(`created` AS CHAR(100)), \'%M %e %Y %h:%i%p\'))
                                AS created_at'
// doesn't work
UNIX_TIMESTAMP(STR_TO_DATE(`created`, '%M %e %Y %h:%i%p'))
                                AS created_at

没有``不能正常工作,我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

我不明白为什么你需要将DATETIME转换为TIMESTAMP。

您可以使用INT(11)字段来存储使用函数UNIX_TIMESTAMP(your_datetime_field)从DATETIME转换的UNIX TIMESTAMP。

请注意,根据文档:http://dev.mysql.com/doc/refman/5.5/en/datetime.html

  

DATETIME类型用于包含日期和时间部分的值。 MySQL以'YYYY-MM-DD HH:MM:SS'格式检索并显示DATETIME值。支持的范围是'1000-01-01 00:00:00'到'9999-12-31 23:59:59'。

     

TIMESTAMP数据类型用于包含日期和时间部分的值。 TIMESTAMP的范围为'1970-01-01 00:00:01'UTC到'2038-01-19 03:14:07'UTC。

答案 1 :(得分:0)

尝试:

select 
  o1.id, 
  o1.operation_date_time, 
  (unix_timestamp(o2.operation_date_time) - unix_timestamp(o1.operation_date_time)) 
    as duration 
from operations as o1 
  inner join operations as o2
where o1.operation = "START" 
  and o2.operation = "STOP"
  and o1.id = (o2.id - 1);

它应该作为输出给出:

+------+---------------------+----------+
| id   | operation_date_time | duration |
+------+---------------------+----------+
|    1 | 2000-01-01 06:30:45 |     4455 |
|    3 | 2000-01-01 08:18:12 |    11146 |
|    5 | 2000-01-01 15:45:01 |    11792 |
+------+---------------------+----------+
3 rows in set (0.00 sec)