目录
Hive中使用TimeStamp时,时间戳默认是精确到秒的,那在Hive中如何处理需要精确到毫秒的时间戳?如何将13位的时间戳转变为精确到毫秒的各种格式?
Hive中TimeStamp的获取及转换
Hive中使用current_timestamp()函数获取当前时间,精确到毫秒
select current_timestamp();
+--------------------------+--+
| _c0 |
+--------------------------+--+
| 2019-06-02 15:31:33.355 |
+--------------------------+--+
1 row selected (0.316 seconds)
Hive中获取当前时间戳,默认使用unix_timestamp()函数,精确到秒
select unix_timestamp();
+-------------+--+
| _c0 |
+-------------+--+
| 1559460765 |
+-------------+--+
1 row selected (0.194 seconds)
Hive中将时间戳转换为日期类型,默认使用from_unixtime ()
desc function extended from_unixtime;
from_unixtime(unix_time, format) - returns unix_time in the specified format
Example:
> SELECT from_unixtime(0, 'yyyy-MM-dd HH:mm:ss') FROM src LIMIT 1;
'1970-01-01 00:00:00'
第一个参数只能是int类型的时间戳,第二个参数为时间格式的字符串,第二个参数也可以为空,默认时间格式为:yyyy-MM-dd HH:mm:ss
select from_unixtime(unix_timestamp());
+----------------------+--+
| _c0 |
+----------------------+--+
| 2019-06-02 15:34:10 |
+----------------------+--+
1 row selected (0.227 seconds)
select from_unixtime(unix_timestamp(), 'yyyyMMddHHmmss');
+-----------------+--+
| _c0 |
+-----------------+--+
| 20190602153447 |
+-----------------+--+
1 row selected (0.191 seconds)
select from_unixtime(unix_timestamp(), 'yyyy/MM/dd HH:mm:ss');
+----------------------+--+
| _c0 |
+----------------------+--+
| 2019/06/02 15:35:13 |
+----------------------+--+
1 row selected (0.207 seconds)
Hive中获取毫秒级别的时间戳
select current_timestamp() as current_time, cast(current_timestamp() as double) * 1000 as timestamp;
2019-06-02 15:44:23.324 1559461463324
由以上两个结果图片可看出,beeline显示的是科学计算的数字,hue上显示正常
Hive中处理毫秒级别的时间戳
desc function extended to_utc_timestamp;
to_utc_timestamp(timestamp, string timezone) - Assumes given timestamp is in given timezone and converts to UTC (as of Hive 0.8.0)
select to_utc_timestamp(1559461463324, 'GMT');
+--------------------------+--+
| _c0 |
+--------------------------+--+
| 2019-06-02 15:44:23.324 |
+--------------------------+--+
1 row selected (2.745 seconds)
将毫秒级别的时间戳转换为指定格式的毫秒时间,SSS代表毫秒
select date_format(to_utc_timestamp(1559461463324, 'GMT'), 'yyyyMMddHHmmssSSS');
+--------------------+--+
| _c0 |
+--------------------+--+
| 20190602154423324 |
+--------------------+--+
1 row selected (0.323 seconds)
select date_format(to_utc_timestamp(1559461463324, 'GMT'), 'yyyy/MM/dd HH:mm:ss.SSS');
+--------------------------+--+
| _c0 |
+--------------------------+--+
| 2019/06/02 15:44:23.324 |
+--------------------------+--+
1 row selected (0.183 seconds)
总结
-
Hive中获取时间戳的方式为unix_timestamp()函数,该函数只能够精确到秒级别的时间,对于时间精确到要求高的应用则该函数并不适合。
-
Hive获取当前时间毫秒级别的时间戳时需要使用cast函数将current_timestamp()转为double类型并乘以1000,则得到毫秒级别的时间戳。
-
对于Hive库中存储的毫秒精度的时间戳,为了确保时间精度不损失则需要使用to_utc_timestamp()函数,该函数支持毫秒级别的时间错,但需要指定当前时区。