Hive中常用的时间函数

在数仓相关工作中,常常会有一些处理时间字段的需求,比如说,计算两个时间字符串之间的时间间隔(日、小时、分钟、秒等)、针对某个时间字符串进行时间上的加减操作等。Hive提供了一些内置函数能够应对这些需求,但是隔了一段时间不用这些函数,比较容易忘记,所以现对其中的函数做一个总结和记录。

1. unix_timestamp函数

 

unix_timestamp函数的作用是计算传入时间距离1970-01-01 00:00:00的秒数,有三种传参方式:

(1)  unix_timestamp() 不传参数,表示计算当前时刻距离1970-01-01 00:00:00的秒数。

(2) unix_timestamp(String timestamp), 其中timestamp的格式须为yyyy-MM-dd HH:mm:ss,计算传入的时刻距离1970-01-01 00:00:00的秒数。

(3) unix_timestamp(String timestamp, String format), 与(2)类似,不过其中timestamp的格式由参数format指定。

可通过基于函数计算两个日期时间戳之间间隔的秒数、分钟数、小时数。

 

2. from_unixtime函数

from_unixtime函数是根据传入的秒数,计算该秒数表示的时间戳。原理是在1970-01-01 00:00:00的基础上加上该秒数得到新的时间戳。使用方法为from_unixtime(long seconds, String format) , 输出的时间戳格式为由format指定,例如:

from_unixtim(1323308764, 'yyyyMMdd');
from_unixtim(1323308764, 'yyyy-MM-dd');
from_unixtim(1323308764, 'yyyy-MM-dd HH:mm:ss');

3. current_date函数与current_timestamp函数

current_date函数返回当前时刻的日期,格式为yyyy-MM-dd,current_timestamp函数返回当前时刻的时间戳,格式为yyyy-MM-dd HH:mm:ss。

4. date_add函数与date_sub函数

date_add:日期增加函数,返回指定日期增加n天后的日期;date_sub:日期减少函数,返回日期减少n天后的日期;如:

date_add('2021-10-08', 6); // '2021-10-14'  
date_sub('2021-10-31', 10); // '2021-10-21' 

5. 日期比较函数:datediff

 

datediff(String startDate, String endDate);  // 返回startDate与endDate的天数差,startDate - endDate,startDate与endDate的格式均为yyyy-MM-dd;
posted @ 2022-08-04 17:38  任风扬  阅读(1546)  评论(1)    收藏  举报