hive中时间戳与时间字符串相互转换的方法教程

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

一、unix_timestamp 函数用法

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

2、unix_timestamp(string date) 返回 date 对应的时间戳,date 格式必须为 yyyy-MM-dd HH:mm:ss。

matlab 复制代码
hive> select unix_timestamp('2018-06-29 00:00:00');
	OK
	1530201600

3、unix_timestamp(string date, string format) 返回 date 对应的时间戳,date 格式由 format 指定。

matlab 复制代码
hive> select unix_timestamp('2018/06/29 09', 'yyyy/MM/dd HH');
	OK
	1530234000

二、from_unixtime 函数用法

1、from_unixtime(int/bigint timestamp) 返回 timestamp 时间戳对应的日期,格式为 yyyy-MM-dd HH:mm:ss。

matlab 复制代码
hive> select from_unixtime(1000000000);
OK
2001-09-09 09:46:40

2、from_unixtime(int/bigint timestamp, string format) 返回 timestamp 时间戳对应的日期,格式由 format 指定。

matlab 复制代码
hive> select from_unixtime(1000000000, 'yyyy/MM/dd HH');
OK
2001/09/09 09

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

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

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

matlab 复制代码
select
    timestamps,
    from_unixtime(cast(timestamps/1000 as int))
from
    test_table

如何辨别时间戳是秒数还是毫秒数

2001-09-09 09:46:40 ~ 2286-11-21 01:46:40 之间的时间戳,都是10位数。

因此,我们这个时代使用的时间戳一般都是10位。如果遇到13位的时间戳,则为毫秒数。

文章来源: https://www.2cto.com/database/201806/757785.html

相关推荐
TTBIGDATA4 小时前
【Ambari开启Kerberos】KERBEROS SERVICE CHECK 报错
大数据·运维·hadoop·ambari·cdh·bigtop·ttbigdata
码·蚁15 小时前
SpringMVC
数据仓库·hive·hadoop
2021_fc16 小时前
StarRocks技术分享
数据仓库
杂家1 天前
Hadoop完全分布式部署(超详细)
大数据·hadoop·分布式
BD_Marathon1 天前
【Hadoop】hadoop3.3.1完全分布式配置
大数据·hadoop·分布式
Q26433650231 天前
【有源码】基于Hadoop+Spark的起点小说网大数据可视化分析系统-基于Python大数据生态的网络文学数据挖掘与可视化系统
大数据·hadoop·python·信息可视化·数据分析·spark·毕业设计
yumgpkpm2 天前
CMP(类Cloudera CDP 7.3 404版华为泰山Kunpeng)和Apache Doris的对比
大数据·hive·hadoop·spark·apache·hbase·cloudera
呆呆小金人2 天前
SQL字段对齐:性能优化与数据准确的关键
大数据·数据仓库·sql·数据库开发·etl·etl工程师
口_天_光健3 天前
制造企业的数据目录编写
大数据·数据库·数据仓库·数据分析
梦里不知身是客113 天前
spark读取table中的数据【hive】
大数据·hive·spark