在 Hive 3.1.3 中禁止将 DATE/TIMESTAMP 类型转换为 NUMERIC

Casting DATE/TIMESTAMP types to NUMERIC is prohibited in Hive 3.1.3

我正在尝试将日期从字符串格式转换为以毫秒为单位的数字格式,试图保持 还有 .SSS 部分,因为我需要在毫秒持续时间级别处理数据。在 Hive 1.1.0 中,我可以使用以下代码在较新版本中执行此操作,但它不允许我这样做:

select current_timestamp(), unix_timestamp(current_timestamp(), 'yyyy-MM-dd HH:mm:ss.SSS')*1000, cast((cast(date_format(cast(current_timestamp() as string),'yyyy-MM-dd HH:mm:ss.SSS') as timestamp)) as double) * 1000 as time_milliseconds

你能告诉我一个解决方法吗?

谢谢

从字符串中提取毫秒部分并添加到(以秒为单位的时间戳)*1000

select current_timestamp(),

--unix_timestamp returns seconds only    
unix_timestamp(current_timestamp())*1000, --without .SSS * 1000

unix_timestamp(current_timestamp())*1000 +
bigint(regexp_extract(string(current_timestamp()),'\.(\d+)$',1)) --with .SSS

结果:

2021-09-21 13:52:32.034  1632232352000  1632232352034

可能不需要显式转换为 bigint 和字符串。

获取毫秒部分的另一种方法是按点拆分字符串并获取元素 #1:split(current_timestamp(),'\.')[1] 而不是 regexp_extract(string(current_timestamp()),'\.(\d+)$',1):

select ts,  unix_timestamp(ts_splitted[0])*1000, unix_timestamp(ts_splitted[0]) * 1000 + ts_splitted[1]
from
(
select current_timestamp() ts, split(current_timestamp(),'\.') ts_splitted
)s

结果:

2021-09-21 18:21:11.032   1632248471000  1632248471032

我更喜欢这种方法。当然如果你有微秒或纳秒的时间戳,逻辑要根据小数部分的长度做相应的调整。