简体   繁体   中英

Need to subtract some hours from given timestamp in hive

Input: unix_timestamp('01/15/2018 15:26:37', 'mm/dd/YYYY hh:mm:ss')

Expected output is 4 hours delay from above utc input time ie 01/15/2018 11:26:37

I know that there is date_sub function in hive but it is only used to subtract days from the given timestamp. But I need to know if there is a way by which I can subtract hours or minutes or seconds.

I have also tried something like below as EDT timezone is 4 hours behind UTC (but getting wrong output):

SELECT to_date(from_UTC_timestamp(unix_timestamp('01/15/2018 15:26:37', 'mm/dd/YYYY hh:mm:ss')*1000, 'EST6EDT')) as earliest_date; -- OUTPUT: 2017-12-31 (wrong) 

So can anyone help me out with this?

它工作正常。

select from_unixtime(unix_timestamp('01/15/2018 15:26:37', 'MM/dd/yyyy HH:mm:ss')-4*3600, 'MM/dd/yyyy HH:mm:ss') 

In addition to the answer of @StrongYoung .

I find it very useful to define such long expressions as a macros and place in the initialization file (eg hive -i init-file.hql ... ).

hive> create temporary macro sub_hours(dt string, hours int)
from_unixtime(unix_timestamp(dt, 'MM/dd/yyyy HH:mm:ss') - 3600 * hours, 'MM/dd/yyyy HH:mm:ss');
OK
Time taken: 0.005 seconds
hive> select sub_hours("01/01/2019 00:00:00", 5);
OK
12/31/2018 19:00:00
Time taken: 0.439 seconds, Fetched: 1 row(s)

Macros are available starting from Hive 0.12.0, further details can be found here (pay attention to the "bug fixes" section).

Eg Your current time in your specific timezone - 1 hour:

select date_format(
        from_utc_timestamp(CURRENT_TIMESTAMP(),'Europe/Madrid') - INTERVAL 1 hours,
        'yyyy-MM-dd HH:mm:ss')
     as PREVIOUS_HOUR

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM