2011-08-26 14 views
8

Ho un file di log che contiene la colonna timestamp. Il timestamp è in formato unix epoch time.come convertire unix epoch time to date string in hive

Voglio creare una partizione basata su un timestamp con partizioni anno, mese e giorno.

Finora ho fatto questo, ma sta generando un errore.

PARSE ERROR cannot recognize input '(' in column type 

Ecco il mio codice.

from (
     from raw_data 
      MAP ${PREFIX}raw_data.line 
      USING 's3://scripts/clean.py' 
      AS (timestamp STRING, name STRING) 
    ) map_out 
INSERT OVERWRITE TABLE date_base_data_temp PARTITION(year(timestamp), month(timestamp)), day(timestamp))) 
    select map_out.name; 

risposta

24

Oof, che sembra brutto. Provare a utilizzare questa funzione in Hive:

SELECT from_unixtime(unix_timestamp) as new_timestamp from raw_data ... 

O se timestamp è in ms invece di secondi:

SELECT from_unixtime(unix_timestamp DIV 1000) as new_timestamp from raw_data ... 

che converte un timestamp Unix in un AAAA-MM-GG HH: MM: SS, quindi è possibile utilizzare le seguenti funzioni per ottenere l'anno, mese e giorno:

SELECT year(new_timestamp) as year, month(new_timestamp) as month, day(new_timestamp) as day ... 
+0

Grazie! Ho risparmiato molto del mio tempo. Questo e 'esattamente quello che stavo cercando! –

+2

Assicurati che il 'timestamp_value' (qui' unix_timestamp') sia in secondi altrimenti usa 'from_unixtime (timestamp_value DIV 1000)' – narush

+0

Sto ottenendo solo il tempo fino al secondo ma voglio anche ms. Come lo faccio ? – Avinash

4

Con versioni più recenti di Hive e SparkSQL, tipo di dati di data e tipo di fusione opzioni sono disponibili. In seguito dovrebbe funzionare in Hive così come Spark SQL

SELECT cast(from_unixtime(epoch_datetime) as date) from myHiveTable 
2

Se avete bisogno di convertire la data in formato personalizzato, utilizzare questo:

select date_format(from_unixtime(epoch_datetime),'yyyMM') as formatted_date from myHiveTable; 


che restituirà la data come per esempio annoMese 201708

0

L'aggiunta di questa query per la lista in cui il timestamp deve essere convertito ad oggi stringa yyyy-MM-dd per una partizione stringa:

hive> select date_format(from_unixtime(epoch_datetime), 'yyyy-MM-dd') as day from table_name limit 20; 

-- If required, remove the millis precision for timestamps 
hive> select date_format(from_unixtime(cast(epoch_datetime/1000 as bigint)), 'yyyy-MM-dd') as day from table_name limit 20;