Hive的时间函数

1- 获取当前日期,得到 yyyy-mm-dd格式

select current_date;

 2- 获得当前时间的 时间戳

select unix_timestamp();

3- 时间戳和日期的相互转换。 from_unixtime 和  unix_timestamp

   3.1-- from_unixtime -  时间戳(13位) 转 日期

-- 默认日期格式是 yyyy-mm-dd HH:MM:ss
select from_unixtime(1637232609);

-- 第二个参数是,指定的日期格式
select from_unixtime(1637232609, 'yyyyMMdd');
select from_unixtime(1637232609, 'yyyy-MM-dd HH:mm:ss');

 

  3.2- unix_timestamp 日期 转 时间戳。 参数字符串格式必须是 " yyyy-mm-dd hh:mm:ss "

-- 注意输入的格式必须是 "yyyy-mm-dd hh:mm:ss"

select unix_timestamp('2021-11-18 14:23:00');

 灵活利用日期和时间戳的相互转换,我们可以方便的实现按年,按月,按日统计业务。

 比如,表原来的时间字段 A 的值是精确到秒的  '2021-11-18 00:00:00' 。

业务是需要按月统计,你需要一个 'yyyy-mm' 格式的字段值时。就可以先将A 转换为时间戳,在用from_unixtime转化为你想要的 yyyy-mm。

4- to_date :字符串 获取日期 yyyy-mm-dd

--参数必须是 'yyyy-mm-dd'格式的
select to_date('2021-01-01 12:12:12');

Hive的时间函数_第1张图片

5- date_diff : 计算日期差, 返回的是天数差

# 格式可以从 'yyyy-mm-dd hh:mm:ss' 到 'yyyy-mm-dd'

datediff('2020-04-18 00:00:00','2019-11-21 00:00:00');

Hive的时间函数_第2张图片

 6-  date_format : 日期、时间戳、字符串类型格式化输出标准时间格式

-- 日期、时间戳、字符串类型格式化输出标准时间格式
select date_format(current_timestamp(), 'yyyy-MM-dd HH:mm:ss');
select date_format(current_date(), 'yyyyMMdd');
select date_format('2021-06-01', 'yyyy-MM-dd HH:mm:ss');

跟from_unixtime不一样的是,from_unixtime是将时间戳转化为 标准时间格式

7- 查询 月几号的

-- 格式 从 'yyyy-mm-dd hh:mm:ss' 到 'yyyy-mm-dd'

dayofmonth(current_date);

dayofmonth('2021-10-21 00:00');

Hive的时间函数_第3张图片

   每月1号: select date_sub(current_date, dayofmonth(current_date)-1)

select date_sub(current_date, dayofmonth(current_date)-1)

select date_sub('2021-10-21 00:00', dayofmonth('2021-10-21 00:00')-1)

Hive的时间函数_第4张图片

 下个月1号

select add_months(date_sub(current_date,
dayofmonth(current_date)-1), 1)

你可能感兴趣的:(hive,hive,大数据)