我提出了三种不同的方法来将您的字符串转换为时间戳。如果您的表定义为 STORED AS TEXTFILE 以外的表,则前两个适用,如果您可以使用 LazySimpleSerDe(与 STORED AS TEXTFILE 相同),则第三种方法适用,在这种情况下,SerDe 将在尽可能低的 livel 上进行转换。
选择中的转化:
select last_updated as original_last_updated, --initial string
--1st method (preferable, because it is not using SimpleDateFormat(which is really not so simple) class internally)
--you can additionally apply timestamp() construct, though in Hive String in proper format is fully interchangeable
regexp_replace(last_updated,'^(\\d{4}-\\d{2}-\\d{2})T(\\d{2}:\\d{2}:\\d{2})','$1 $2') as result1,
--2nd method is using SimpleDateFormat under the hood, easier to read
from_unixtime(unix_timestamp(last_updated,"yyyy-MM-dd'T'HH:mm:ss")) as result2
from
(select '2021-08-04T06:48:55' as last_updated ) s
结果:
original_last_updated result1 result2
2021-08-04T06:48:55 2021-08-04 06:48:55 2021-08-04 06:48:55
第三种方法 - 使用 LazySimpleSerDe:
如果您使用的是 LazySimpleSerDe(存储为文本文件),则可以通过向 SerDe 属性"timestamp.formats" 提供格式来支持替代时间戳格式(自 1.2.0 版起,HIVE-9298) .尝试将"yyyy-MM-dd'T'HH:mm:ss" 作为属性值并将列类型定义为timestamp。虽然 LazySimpleSerDe 不识别引号,但可以在您拥有带有未引用值的简单 CSV 的情况下使用。