Hive/SparkSQL:如何将 Unix 时间戳转换为时间戳(而不是字符串)?

2024-03-09

我以为这很容易......

在 Hive/SparkSQL 中,如何将 unix 时间戳[注 1] 转换为timestamp数据类型?

(注1:即自1970年1月1日起的秒/毫秒数)

我想from_unixtime()会这样做,但它返回一个字符串 而不是时间戳。下面的实验说明了这个问题

第0步:准备

select 
  from_unixtime(1508673584) as fut;

Result:

-----------------------
| fut                 |
| ------------------- |
| 2017-10-22 11:59:44 |
-----------------------

步骤 1:创建一个表,其中包含结果from_unixtime()

create table test
select 
  from_unixtime(1508673584) as fut;

步骤 2:检查列的数据类型fut

describe test;

Result:

----------------------------------
| col_name | data_type | comment |
| -------- | --------- | ------- |
| fut      | string    | <null>  |
----------------------------------

我也尝试过这个

select 
  from_utc_timestamp(1508618794*1000, 'EDT');

根据手册(链接here https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions),这应该有效。因为它 指出:

将 UTC 时间戳*转换为给定时区(从 Hive 0.8.0 开始)。 * timestamp 是一个原始类型,包括时间戳/日期, tinyint/smallint/int/bigint、float/double 和decimal。分数 值被视为秒。整数值被视为 毫秒.. 例如 from_utc_timestamp(2592000.0,'PST'), from_utc_timestamp(2592000000,'PST') 和 from_utc_timestamp(timestamp '1970-01-30 16:00:00','PST') 全部返回时间戳 1970-01-30 08:00:00

但是,我得到了一个错误

Error: org.apache.spark.sql.AnalysisException: 
  cannot resolve 'from_utc_timestamp((1508618794 * 1000), 'EDT')' 
  due to data type mismatch: 
  argument 1 requires timestamp type, 
  however, '(1508618794 * 1000)' is of int type.; line 2 pos 2;
'Project [unresolvedalias(from_utc_timestamp((1508618794 * 1000), EDT), None)]
+- OneRowRelation$

SQLState:  null
ErrorCode: 0    

(我自己在这里提供答案。)

答案是使用cast()。这对两者都有效date and timestamp

select 
  from_unixtime(1508673584)                    as fut,
  cast(from_unixtime(1508673584) as date)      as futAsDate,
  cast(from_unixtime(1508673584) as timestamp) as futAsTimestamp;

Result:

------------------------------------------------------------
| fut                 | futAsDate  | futAsTimestamp        |
| ------------------- | ---------- | --------------------- |
| 2017-10-22 11:59:44 | 2017-10-22 | 2017-10-22 11:59:44.0 |
------------------------------------------------------------

数据类型验证

create table test2
select 
  from_unixtime(1508673584)                    as fut,
  cast(from_unixtime(1508673584) as date)      as futAsDate,
  cast(from_unixtime(1508673584) as timestamp) as futAsTimestamp;

And then

describe test2;  

Result:

----------------------------------------
| col_name       | data_type | comment |
| -------------- | --------- | ------- |
| fut            | string    | <null>  |
| futAsDate      | date      | <null>  |
| futAsTimestamp | timestamp | <null>  |
----------------------------------------
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Hive/SparkSQL:如何将 Unix 时间戳转换为时间戳(而不是字符串)? 的相关文章

随机推荐