我正在尝试在时间戳之间进行减法,并希望将时间戳转换为可以转换为分钟的形式。
我使用regexp_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_replace()或其他任何函数将这两个时间戳转换为秒?
谢谢!
首先,unix_timestamp
返回从unix纪元过去的秒数。它不会忽略毫秒。这就是为什么如果您想要以秒为单位的纪元时间,则只能提取的原因'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_replace进行转换。尽管正则表达式允许识别和解析最复杂的字符串。
另外,您可以尝试使用一种模式进行转换,如果返回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'))
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句