设为首页 加入收藏

TOP

hive 中时间戳与时间字符串的相互转换
2018-12-30 13:04:52 】 浏览:428
Tags:hive 时间 字符串 相互 转换
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HappyRocking/article/details/80854778

时间戳是数据库常用的存放日期的形式之一,表示从 UTC 时间’1970-01-01 00:00:00’开始到现在的秒数,与常规时间格式如 ‘2018-01-01 00:00:00’可以相互转换,方法如下。

一、unix_timestamp 函数用法

1、unix_timestamp() 返回当前时间戳。另外,current_timestamp() 也有同样作用。

hive> 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

hive> 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 指定。

hive> 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。

hive> 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 指定。

hive> select from_unixtime(1000000000, 'yyyy/MM/dd HH');
OK
2001/09/09 09
Time taken: 0.24 seconds, Fetched: 1 row(s)

三、“毫秒”时间戳的特殊处理

有时候,存放的时间戳不是秒数,而是毫秒数,因此转换前需要除以1000。

同理,时间转成时间戳时,也需要乘以 1000。

select
    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位的时间戳,则为毫秒数。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Hive中文注释问题 下一篇Hbase表映射成hive中

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目