Apache Hive:如何将字符串转换为时间戳?

Apache Hive: How to convert string to timestamp?

我正在尝试将 REC_TIME 列中的字符串转换为配置单元中的时间戳格式。

示例:7 月 31 日星期日 09:28:20 UTC 2016 => 2016-07-31 09:28:20

SELECT xxx, UNIX_TIMESTAMP(REC_TIME, "E M dd HH:mm:ss z yyyy") FROM wlogs LIMIT 10;

当我执行上面的 SQL 它 returns 一个 NULL 值。

试试这个:

select from_unixtime(unix_timestamp("Sun Jul 31 09:28:20 UTC 2016","EEE MMM dd HH:mm:ss zzz yyyy"));

如果您的 Hive 群集具有 UTC 时区,则此方法工作正常。假设您的服务器处于 CST,那么您需要执行以下操作才能到达 UTC;

select to_utc_timestamp(from_unixtime(unix_timestamp("Sun Jul 31 09:28:20 UTC 2016","EEE MMM dd HH:mm:ss zzz yyyy")),'CST');

希望对您有所帮助。

编辑 Hive 日期函数对模式使用 JAVA 简单日期格式器。模式请参考 this

请注意我的计算机在 PDT 上运行

[cloudera@quickstart ~]$ date +%Z
PDT

因此 UTC 时间转换为 2:28:20 PDT。无论如何,这不是重点。 您正在使用 HH 数小时,使用 hh 并且您一个月至少需要 3 M。

0: jdbc:hive2://quickstart:10000/default> select from_unixtime(unix_timestamp("Sun Jul 31 09:28:20 UTC 2016", 'E MMM dd hh:mm:ss z yyyy')) as date;
+----------------------+--+
|         date         |
+----------------------+--+
| 2016-07-31 02:28:20  |
+----------------------+--+