hive将时间字符串转换为timestamp的几种写法
时间:2025-06-24 12:41:55 来源:新华社
【字体:  

写法一。

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

写法二。

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

写法三。

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

我觉得这种方法太复杂了。

使用的函数。

unix_timestamp。

  • 函数签名。
bigint unix_timestamp。(。string datetime, string。 format。)。
  • 函数返回值。
    bigint类型的时间戳整数。

  • 函数入参。
    第一个参数是string类型的时间,比如’2024-01-10 20:44:00’。
    第二个参数是string类型的时间格式格式,比如’yyyy-MM-dd HH:mm:ss’。

  • 函数使用。

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

from_unixtime。

  • 函数签名。
string from_unixtime。(。bigint time, string fromat。)。
  • 函数返回值。

  • 函数参数。
    bigint类型的时间戳。
    string类型格式,用于指定函数返回值的格式,￰可以省略c;如果省略󿀌则默认为’yyyy-MM-dd HH:mm:ss’。

  • 函数使用。

select。from_unixtime。(。1701619200。, 'yyyy-MM-dd HH:mm:ss')。;
-- 省略format。select。from_unixtime。(。1701619200。)。;

测试。

以下字符串可作为输入进行测试。
beeline客户端测试了以下城市的字符串,均可转换为timestamp,而且时间精度不会丢失。

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。:。02024。-。01。-。10。20。:。44。:。00.048。

参考。

unix_timestamp 时间戳函数(hive)

[责任编辑:百度一下]
检察日报数字报 | 正义网 |
Copyrights©最高人民检察院 All Rights Reserved.