您现在的位置是:首页 > 数据处理

hive-时间格式转化

batsom2022-03-21数据处理

简介hive 时间格式转化

时间格式转化

一、unix_timestamp函数用法
1、unix_timestamp() 得到当前时间戳
2、如果参数date满足yyyy-MM-dd HH:mm:ss形式,则可以直接unix_timestamp(string date) 得到参数对应的时间戳
3、如果参数date不满足yyyy-MM-dd HH:mm:ss形式,则我们需要指定date的形式,在进行转换
select unix_timestamp('2009-03-20')   --1237507200
select unix_timestamp('2009-03-20 00:00:00', 'yyyy-MM-dd HH:mm:ss') --1237507200
select unix_timestamp('2009-03-20 00:00:01', 'yyyy-MM-dd HH:mm:ss') --1237507201
二、from_unixtime函数用法
select from_unixtime(1237507201,'yyyy-MM-dd HH:mm:ss') -- 2009-03-20 00:00:01
select from_unixtime(1237507200,'yyyy-MM-dd HH:mm:ss') -- 2009-03-20 00:00:00
 
常用的插入时间为当前系统时间 转换成距离1970的时间戳,再转换成当前时间
select FROM_UNIXTIME(UNIX_TIMESTAMP() ,'yyyy-MM-dd HH:mm:ss') AS W_INSERT_DT

总结

1.Hive中获取时间戳的方式为unix_timestamp()函数,该函数只能够精确到秒级别的时间,对于时间精确到要求高的应用则该函数并不适合。

2.Hive获取当前时间毫秒级别的时间戳时需要使用cast函数将current_timestamp()转为double类型并乘以1000,则得到毫秒级别的时间戳。

3.对于Hive库中存储的毫秒精度的时间戳,为了确保时间精度不损失则需要使用to_utc_timestamp()函数,该函数支持毫秒级别的时间错,但需要指定当前时区。

Hive中TimeStamp获取及转换
 
1.Hive中使用current_timestamp()函数获取当前时间
 
select current_timestamp();   --2019-07-04 10:17:08.429275000
 
使用Hive的current_timestamp()函数获取到当前的时间精确到毫秒。
 
2.Hive中获取当前时间戳,默认使用unix_timestamp()函数
 
select unix_timestamp(current_timestamp());   --1562235446
 
使用Hive的unix_timestamp()函数获取到当前的时间戳为10位的bigint类型数值,该数值只精确到秒级别。
 
3.Hive中将时间戳转换为日期类型,默认使用from_unixtime ()
 
select from_unixtime(1543735779, 'yyyy-MM-dd HH:mm:ss:SSS');
--2019-07-04 10:17:26:000
 
上面的转换结果可以看到时间的毫秒是无法正常获取到,因为时间戳只是精确到秒级别的,from_unixtime()函数也只支持秒级别的时间戳转换。
 
4.Hive中获取毫秒级别的时间戳
 
select current_timestamp(),
cast(current_timestamp() as double) as 'timestamp';

current_timestamp()    timestamp
     current_timestamp()              timestamp
1    2019-07-04 10:20:34.743662000    1562235634.7436621
这里可以看到获取到了一个13位的数值,该数值精确到毫秒即为当前的时间的时间戳。
5.Hive中处理毫秒级别的时间戳
select to_utc_timestamp(1543736635303, 'GMT');
--2018-12-02 15:43:55.303    --用impala不行
使用Hive提供的to_utc_timestamp()函数将毫秒级别的时间戳转换为相应的时间并且精确到了毫秒,与上一步获取时间戳的时间一致。

时间戳转格式化
select from_unixtime( cast(1616568397888/1000 as int),'yyyyMMddHHmmss');





 

郑重声明:

本站所有活动均为互联网所得,如有侵权请联系本站删除处理

随便看看

文章排行

本栏推荐

栏目更新