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

您所在的位置:网站首页 hive的string类型 hive 中时间戳与时间字符串的相互转换

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

2024-07-13 04:29| 来源: 网络整理| 查看: 265

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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3