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

相关推荐
鹿衔`16 小时前
Hadoop HDFS 核心机制与设计理念浅析文档
大数据·hadoop·hdfs
`林中水滴`17 小时前
数仓系列:一文读懂仓湖一体架构
数据仓库
Justice Young19 小时前
Sqoop复习笔记
hadoop·笔记·sqoop
大厂技术总监下海20 小时前
从Hadoop MapReduce到Apache Spark:一场由“磁盘”到“内存”的速度与范式革命
大数据·hadoop·spark·开源
zgl_2005377921 小时前
ZGLanguage 解析SQL数据血缘 之 Python提取SQL表级血缘树信息
大数据·数据库·数据仓库·hive·hadoop·python·sql
Justice Young2 天前
Hive第四章:HIVE Operators and Functions
大数据·数据仓库·hive·hadoop
LF3_2 天前
hive,Relative path in absolute URI: ${system:user.name%7D 解决
数据仓库·hive·hadoop
德彪稳坐倒骑驴2 天前
Hive SQL常遗忘的命令
hive·hadoop·sql
Justice Young2 天前
Hive第六章:Hive Optimization and Miscellaneous
数据仓库·hive·hadoop
Justice Young2 天前
Hive第五章:Integeration with HBase
大数据·数据仓库·hive·hbase