将字符串值转换为时间戳格式

时间:2019-01-29 09:07:54

标签: mysql datetime

我有类似的数据:

trx_date  trx_time
181125    114204
181125    230552
181125    172338
181125    083516
181125    090308

我想从yymmdd和hhiiss转换为时间戳格式yyyy-MM-dd HH:mm:ss

我尝试使用unix时间戳语法:

select 
  trx_date,
  trx_time,
  from_unixtime(unix_timestamp(concat(trx_date, trx_time), 'yyMMddHHmmss'),'yyyy-MM-dd HH:mm:ss')
FROM table 
limit 100;

但是它抛出了error 1064,怎么可能出问题了?

1 个答案:

答案 0 :(得分:1)

它看起来不像Unix时间戳,但日期存储为yymmddhhmmss。尝试像这样转换:

SELECT STR_TO_DATE(CONCAT('20', trx_date, trx_time), '%Y%m%d%H%i%s')
FROM (
    SELECT '181125' AS trx_date, '114204' AS trx_time UNION ALL
    SELECT '181125' AS trx_date, '230552' AS trx_time UNION ALL
    SELECT '181125' AS trx_date, '172338' AS trx_time UNION ALL
    SELECT '181125' AS trx_date, '083516' AS trx_time UNION ALL
    SELECT '181125' AS trx_date, '090308' AS trx_time
) AS x
-- 2018-11-25 11:42:04 etc

请注意,日期有两位数字的年份,模棱两可。上面的示例假设所有日期均为20xx。