hive转换unix时间戳进行计算

gcxthw6b  于 2021-06-24  发布在  Hive
关注(0)|答案(2)|浏览(376)

我正在尝试执行时间戳之间的减法运算,并希望将时间戳转换为可以转换为分钟的形式。
我使用regexp\u replace将时间戳转换为以下形式:

2020-06-20T17:25:59:378Z

下面的代码将它转换为秒

unix_timestamp(regexp_replace(value,'(.*?)T(.*?):([^:]*?)Z$','$1 $2\\.$3'))

我还有另外两个时间戳要转换为秒,例如:

2020-03-19 15:45:33
03-19-2020 11:07:25:103

如何使用regexp\u replace()或任何其他函数将这两个时间戳转换为秒?
谢谢您!

zbq4xfa0

zbq4xfa01#

对于第一个,您真的不需要使用regex\u replace。

select unix_timestamp('2020-06-20T17:25:59:378Z','yyyy-MM-dd'T'HH:mm:ss.SSSZ');

另外两个呢

select unix_timestamp('2020-03-19 15:45:33', 'yyyy-MM-dd HH:mm:ss');
select unix_timestamp('03-19-2020 11:07:25:103', 'MM-dd-yyyy HH:mm:ss:SSS');
mftmpeh8

mftmpeh82#

首先, unix_timestamp 返回从unix epoch传递的秒数。它忽略毫秒。这就是为什么如果你想要以秒为单位的历元时间,你只能提取 'yyyy-MM-dd HH:mm:ss' .
第二,如果在单个数据集中有所有这些不同的格式,并且希望将它们全部转换,则可以使用case语句检查模式并相应地转换:

with your_data as ( --This is your data example
select stack(3,
             '2020-06-20T17:25:59:378Z',
             '2020-03-19 15:45:33',
             '03-19-2020 11:07:25:103'
            ) as str
)

select case when str rlike '^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}:\\d{2}:\\d{2})' --matches first two strings
             then unix_timestamp(regexp_replace(str,'^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}:\\d{2}:\\d{2})','$1 $2'))
            when str rlike '^(\\d{2})-(\\d{2})-(\\d{4})[T ](\\d{2}:\\d{2}:\\d{2})' --matches third string, allows T or space after date
             then unix_timestamp(regexp_replace(str,'^(\\d{2})-(\\d{2})-(\\d{4})[T ](\\d{2}:\\d{2}:\\d{2})','$3-$1-$2 $4'))
        end result_unix_timestamp
from your_data

退货:

result_unix_timestamp
1592673959
1584632733
1584616045

您可以通过相应的转换向案例添加更多的模式,并以这种方式转换所有可能的案例。当然,并非所有情况下都应该使用regex\u replace进行转换。尽管regex允许识别和解析最复杂的字符串。
您还可以尝试使用一种模式进行转换,如果它返回 null 然后尝试使用其他模式进行转换,依此类推:

coalesce(unix_timestamp(regexp_replace(str,'^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}:\\d{2}:\\d{2})','$1 $2')),
         unix_timestamp(regexp_replace(str,'^(\\d{2})-(\\d{2})-(\\d{4})[T ](\\d{2}:\\d{2}:\\d{2})','$3-$1-$2 $4'))
        )

相关问题