hive时间戳函数
(转载):
时间戳是常⽤的存放⽇期的形式之⼀,表⽰从 UTC 时间’1970-01-01 00:00:00’开始到现在的秒数,与常规时间格式如 ‘2018-01-01 00:00:00’可以相互转换,⽅法如下。
⼀、unix_timestamp 函数⽤法
1、unix_timestamp() 返回当前时间戳。另外,current_timestamp() 也有同样作⽤。
1 2 3 4 5hive> select unix_timestamp();
unix_timestamp(void) is deprecated. Use current_timestamp instead. OK
1530241405
Time taken: 0.237 seconds, Fetched: 1 row(s)
2、unix_timestamp(string date) 返回 date 对应的时间戳,date 格式必须为 yyyy-MM-dd HH:mm:ss。
1 2 3 4hive> select unix_timestamp('2018-06-29 00:00:00'); OK
1530201600
Time taken: 0.232 seconds, Fetched: 1 row(s)
3、unix_timestamp(string date, string format) 返回 date 对应的时间戳,date 格式由 format 指定。
1 2 3 4hive> select unix_timestamp('2018/06/29 09', 'yyyy/MM/dd HH'); OK
1530234000
Time taken: 0.755 seconds, Fetched: 1 row(s)
⼆、from_unixtime 函数⽤法
1、from_unixtime(int/bigint timestamp) 返回 timestamp 时间戳对应的⽇期,格式为 yyyy-MM-dd HH:mm:ss。
1 2 3 4hive> select from_unixtime(1000000000); OK
2001-09-09 09:46:40
Time taken: 0.316 seconds, Fetched: 1 row(s)
2、from_unixtime(int/bigint timestamp, string format) 返回 timestamp 时间戳对应的⽇期,格式由 format 指定。
1 2 3 4hive> select from_unixtime(1000000000, 'yyyy/MM/dd HH'); OK
2001/09/09 09unix时间戳转换日期格式
Time taken: 0.24 seconds, Fetched: 1 row(s)
三、“毫秒”时间戳的特殊处理
有时候,存放的时间戳不是秒数,⽽是毫秒数,因此转换前需要除以1000。同理,时间转成时间戳时,也需要乘以 1000。
1select
2 3 4 5 6 7 8    timestamps,
from_unixtime(cast(timestamps/1000 as int))
from
test_table
where
timestamps > UNIX_TIMESTAMP('2018-06-25 09:00:00') * 1000 and timestamps < UNIX_TIMESTAMP('2018-06-25 09:10:00') * 1000
结果为:
如何辨别时间戳是秒数还是毫秒数
2001-09-09 09:46:40 ~ 2286-11-21 01:46:40 之间的时间戳,都是10位数。
因此,我们这个时代使⽤的时间戳⼀般都是10位。如果遇到13位的时间戳,则为毫秒数。