1.unix_timestamp
1.1语义
返回时间的时间戳,该函数只能够精确到秒级别的时间
UNIX_TIMESTAMP() :若无参数调用,则返回一个 Unix timestamp (‘1970-01-01 00:00:00’ GMT 之后的秒数) 作为无符号整数,得到当前时间戳
1.2:实例
hive> SELECT unix_timestamp() ; (执行使得时间:2009-08-06 10:10:40)
->1249524739
hive> SELECT unix_timestamp('2009-08-06','yyyy-MM-dd') ;
->1249488000
hive> SELECT unix_timestamp('2009-0806','yyyy-MMdd') ;
->1249488000
2.from_unixtime
1.1语义
将时间戳(精确到秒级别的时间)转化为某种格式的日期。
1.2语法
语法:from_unixtime(timestamp ,date_format)
即from_unixtime(时间戳 ,日期格式)
参数说明
timestamp :时间戳,可为一串数字,也可为字段。
date_format:时间格式,不填默认为%Y-%m-%d %H:%i:%s的格式。
补充:其中timestamp 是10位的时间戳值,即1970-1-1至今的秒,而13位的所谓毫秒的是不可以的。
对于13位时间戳,需要截取,然后转换成bigint类型,因为from_unixtime类第一个参数只接受bigint类型。例如:
select from_unixtime(cast(substring(tistmp,1,10) as bigint),‘yyyy-MM-dd’)
1.3:实例
hive>SELECT from_unixtime( 1249488000, 'yyyy-MM-dd');
->2009-08-05
hive>SELECT from_unixtime( 1249488000, 'yyyy年MM月dd日');
->2009年08月05日
select from_unixtime(cast(substring(tistmp,1,10) as bigint),'yyyy-MM-dd HH:mm:ss')---此处tistmp为string类型
select from_unixtime(cast(tistmp/1000 as bigint),'yyyy-MM-dd HH:mm:ss')---此处tistmp为bigint类型
3.实战
3.1需求:
现在有这样一个时间’2021-0320’,需要将这个时间变成2021/03/20;
3.2分析:
首先想到data_format函数,可以将时间转换成某种格式,可是传入的应该是标准形式的时间参数,显然’2021-0320’,不符合时间格式(此为标准格式2021-03-20);此时我们可以想到用unix_timestamp,from_unixtime函数,先用unix_timestamp函数把’2021-0320’转换为时间戳,再用from_unixtime函数把时间戳转化为2021/03/20格式的时间;
3.3具体实现:
hive>SELECT UNIX_TIMESTAMP('2021-0320','yyyy-MMdd');
->1616198400
hive>SELECT from_unixtime(1616198400,'yyyy/MM/dd');
->2021/03/20
hive>SELECT from_unixtime(UNIX_TIMESTAMP('2021-0320','yyyy-MMdd'),'yyyy/MM/dd');
->2021/03/20
补充:date_format函数(根据格式整理日期)
hive (gmall)> select date_format('2021-03-20','yyyy/MM/dd');
2021/03/20