Hive—date函数详解

引言

  在hive中我们经常需要处理日期数据,hive内置了3个日期函数,其格式只能为yyyy-MM-dd格式或者yyyy-MM-dd HH:mm:ss'格式

常用date函数

日期比较函数:datediff

语法

datediff(string enddate,string startdate)
说明:返回结束日期enddate减去开始日期startdate的天数
返回值类型:int

示例

  1. 返回天数为正
hive> select datediff('2022-01-02','2022-01-01'); 
1

2.返回天数为负数

hive>select datediff('2022-01-01','2022-01-03'); 
-2
  1. 返回最近一周的数据
hive>select * from table_01 where datediff(current_timestamp,create_time)<=7;

其中:
create_timetable_01中的时间字段;
current_timestamp为放回当前时间;

日期增加函数:date_add

语法

date_add(string startdate,int days)
说明:返回开始日期startdat增加天数days后的日期,days可以正负数,若days>0,则表示增加days的日期。若days<0,则表示减少days的日期。
返回值类型:string

示例

  1. 返回2天日期
hive>select date_add('2022-01-01',2);
2022-01-03
  1. 返回一周后那一天的预测数据
hive>select * from table_01 where create_time = date_add(current_timestamp,7);

其中:
create_timetable_01中的时间字段;
current_timestamp为放回当前时间;

日期减少函数:date_sub

语法

date_sub(string startdate,int days)
说明:返回开始日期startdat减去天数days后的日期,days可以正负数,若days>0,则表示减少days的日期。若days<0,则表示增加days的日期。
返回值类型:string

  1. 返回9天前的日期
hive>select date_sub('2022-01-10',9);
2022-01-01
  1. 返回一周前当天的数据
hive>select * from table_01 where create_time=date_sub(current_timestamp,7);

其中:
create_timetable_01中的时间字段;
current_timestamp为放回当前时间;

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容