Hive 时间戳和日期相互转换

时间戳转成日期

select distinct from_unixtime(1441565203,‘yyyy/MM/dd HH:mm:ss’) from test_date;

日期转成时间戳

select distinct unix_timestamp(‘20111207 13:01:03’) from test_date; // 默认格式为“yyyy-MM-dd HH:mm:ss“

select distinct unix_timestamp(‘20111207 13:01:03’,‘yyyyMMdd HH:mm:ss’) from test_date;

yyyymmdd和yyyy-mm-dd日期之间的切换

方法1: from_unixtime+ unix_timestamp
–20181205转成2018-12-05
select from_unixtime(unix_timestamp(‘20181205’,‘yyyymmdd’),‘yyyy-mm-dd’) from dual;

–2018-12-05转成20181205
select from_unixtime(unix_timestamp(‘2018-12-05’,‘yyyy-mm-dd’),‘yyyymmdd’) from dual;

方法2: substr + concat
–20181205转成2018-12-05
select concat(substr(‘20181205’,1,4),’-’,substr(‘20181205’,5,2),’-’,substr(‘20181205’,7,2)) from dual;

–2018-12-05转成20181205
select concat(substr(‘2018-12-05’,1,4),substr(‘2018-12-05’,6,2),substr(‘2018-12-05’,9,2)) from dual;
注:

1.值得注意的是,时间戳有可能是毫秒级的,然后这时候直接使用from_unixtime(1441565203,‘yyyy/MM/dd HH:mm:ss’)的话就会得到很奇怪的日期了,这时候要这样from_unixtime(cast(151331629920/1000 as int)),同样的,时间转成毫秒级的时间戳也要乘以1000,如:unix_timestamp(‘2018-12-18 00:38:50’)*1000

2.如何区分时间戳是秒级还是毫秒级呢?一般来说,常见的时间戳是10位数的,13位数的时间戳就是毫秒级的
Hive 时间戳和日期相互转换_第1张图片

你可能感兴趣的:(Hive,大数据进击之路)