hive 中时间戳与时间字符串的相互转换

时间戳是数据库常用的存放日期的形式之一,表示从 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位的时间戳,则为毫秒数。

  • 10
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值