在Hive中将dd / mm / yyyy / hh / mm / ss格式更改为yyyymm

时间:2019-05-24 18:44:18

标签: date hive timestamp hiveql impala

我现在正在使用Hive。我有一列字符串(列A),其格式为11/9/2009 0:00:00。我想提取yyyymm。即我希望上面的字符串为200909。我尝试了两种都不起作用的方法。

我尝试使用两种不同的方法转换字符串

       concat(year(Column A),lpad(month(Column A),2,0))


       convert(datetime, Column A)

对于我收到的第一行代码:所有行均为NULL

第二个是我收到的:

  

遇到:DATETIME预期:ALL,CASE,CAST,DEFAULT,DISTINCT,   EXISTS,FALSE,IF,INTERVAL,NOT,NULL,REPLACE,TRUNCATE,TRUE,   标识的原因:异常:语法错误

2 个答案:

答案 0 :(得分:2)

使用unix_timestamp(string date, string pattern)given date format转换为从1970-01-01开始的秒数。然后使用from_unixtime()转换为required format

select  from_unixtime(unix_timestamp( '11/9/2009 0:00:00','dd/MM/yyyy HH:mm:ss'), 'yyyyMM');

结果:

200909

另请参阅:Impala data and time functionsHive date functions

另一种解决方案,可在Hive中使用:

select  concat(regexp_extract('11/9/2009 0:00:00','(\\d{1,2})/(\\d{1,2})/(\\d{4})',3),lpad(regexp_extract('11/9/2009 0:00:00','(\\d{1,2})/(\\d{1,2})/(\\d{4})',2),2,0))

答案 1 :(得分:1)

由于我正尝试将字符串转换为YYYYMM,因此必须使用以下对我有用的内容:

      'concat(substr(Column A, instr(Column A, ' ')-4, 4),substr(Column A, instr(Column A, ' /')+1, 2))'