hive将时间字符串转换为timestamp的几种写法

写法一

sql 复制代码
select from_utc_timestamp(from_unixtime(unix_timestamp('2023-8-7 9:38:10 UTC+08:00', 'yyyy-MM-dd HH:mm:ss')), 'UTC');

写法二

sql 复制代码
select cast(unix_timestamp('2023-8-7 9:38:10 UTC+08:00', 'yyyy-MM-dd HH:mm:ss') as timestamp);

写法三

sql 复制代码
select cast(trim(split(upper('2023-10-31 4:46:40 UTC+0800'), 'UTC')[0]) as timestamp); 

这种方式我觉得过于复杂了。

使用到的函数

unix_timestamp

  • 函数签名
bash 复制代码
bigint unix_timestamp(string datetime, string format)
  • 函数返回值

    bigint类型的时间戳整数

  • 函数入参

    第一个参数是string类型的时间,比如'2024-01-10 20:44:00'。

    第二个参数是string类型的时间格式化的格式,比如'yyyy-MM-dd HH:mm:ss'。

  • 函数使用

bash 复制代码
-- 将给定时间字符串转换为指定格式的时间戳数字
select unix_timestamp('2023-12-4 4:45:12 UTC+08:00', 'yyyy-MM-dd HH:mm:ss');
-- 输出为1701619200
bash 复制代码
-- 获取当前时间戳
select unix_timestamp();
  • 注意点
    方法的返回值在spark中可以直接强转为timestamp。
    在hive中不能直接转为timestamp,强转会转为很奇怪的时间。
    如果要在hive中将此函数返回值转为timestamp,则需要使用cast函数转为timestamp。

from_unixtime

  • 函数签名
bash 复制代码
string from_unixtime(bigint time, string fromat)
  • 函数返回值

  • 函数参数

    bigint类型的时间戳。

    string类型的格式,用于指定函数返回值的格式,可以省略,如果省略,则默认为'yyyy-MM-dd HH:mm:ss'

  • 函数使用

bash 复制代码
select from_unixtime(1701619200, 'yyyy-MM-dd HH:mm:ss');
bash 复制代码
-- 省略format
select from_unixtime(1701619200);

测试

可以使用以下字符串作为输入进行测试。

以下各市的字符串经过在beeline客户端进行测试,均能转换为timestamp,且时间精度不会丢失

sql 复制代码
2023-8-31 15:40:56

-- 能够将带有UTC格式的字符串转换为时间戳,然后再转换为timestamp。
-- 但是会有8个小时的误差,上述的方法貌似是直接把UTC字符串给去掉了。                                                                                                                                                          
2023-12-4 4:45:12 UTC+0800

2023-10-17 3:38:1 UTC+0800

2023-5-3 13:7:0

2024-01-10 20:44:00.048

参考

unix_timestamp 时间戳函数用法(hive)

相关推荐
白日与明月5 小时前
Hive分桶机制应用
数据仓库·hive·hadoop
Msshu1236 小时前
XSP25全协议 100W PD快充诱骗芯片_串口读电压电流信息
hive·云计算·json·database·memcached
水火既济__6 小时前
大数据hive_mr压缩问题
大数据·hive·mr
水火既济__6 小时前
hive中加载json数据建表(大规模)
hive·hadoop·json
承渊政道10 小时前
数据删了不等于销毁:KingbaseES敏感数据物理擦除实战指南
运维·服务器·数据库·数据仓库·安全·oracle·业界资讯
修先生1 天前
Hive Udf函数AES加密
hive·aes·udf
SeaTunnel1 天前
Apache SeaTunnel 4 月有何新动作?连接器增强与 Zeta 稳定性提升等亮点速览
大数据·数据仓库·spark·apache·seatunnel
Volunteer Technology1 天前
HDFS源码(二)
大数据·hadoop·hdfs
承渊政道1 天前
Oracle迁移避坑:一个(+)写错,LEFT JOIN可能变INNER JOIN
运维·服务器·数据库·数据仓库·学习·安全·oracle
WL_Aurora1 天前
MapReduce框架原理深度解析 | Shuffle机制、切片分区、Join全攻略
大数据·hadoop·mapreduce