hive 上有没有专门的日期类型?
目前线上使用的hive没有专门的日期类型,我们使用字符串(string)来存储日期类型,比如 '2012-12-29', '2012-12-29 10:00:00'。
我们一般称其中形如 'yyyy-mm-dd' 的数据为 date类型数据,形如 'yyyy-mm-dd HH:MM:SS'的数据为time类型数据。
另外我们经常用一个整数(int) 来表示日期,比如 20121229 表示 '2012-12-29', 形如 'yyyymmdd' 的数据我们一般称为 datekey类型。
自助查询数据中哪些数据是日期类型呢?
一般数据中包含'date', 'time' 等关键字的字段可能是日期类型。
带有'date'关键字的字段(比如 couponbegindate) 一般是形如 ’2012-12-29' 的数据,带有 ’time'关键字的字段(比如couponbegintime)一般是形如 '2012-12-29 10:00:00' 的数据,
带有 'datekey' 关键字的字段一般是形如 ’20121229’ 的数据。
可能存在字段直接命名为 'date' , 由于date是系统关键字,对于这种字段查询时需带上反引号(比如 `date`)。
另外,在分区表当中,分区字段一般有 dt, hour。 其中dt可以认为是 datekey 类型的,比如 " dt=20121229 "。
常用的日期函数有哪些呢?
1.from_unixtime
说明:转化UNIX时间戳(从1970-01-01 00:00:00 UTC到指定时间的秒数)
到当前时区的时间格式
eg:
select
from_unixtime(1356768454, 'yyyyMMdd')
limit 1;
输出结果:20121229
2.unix_timestamp
说明:转换格式为“yyyy-MM-dd HH:mm:ss“的日期到UNIX时间戳。
如果转化失败,则返回0。
如果不加参数的话则返回获得当前时区的UNIX时间戳。
eg:select
unix_timestamp('2012-12-29 13:01:03','yyyy-MM-dd HH:mm:ss')
from dim.city
limit 1;
输出结果:1356757263
3.to_date(string timestamp)
说明:返回日期时间字段中的日期部分。
eg:select
to_date('2012-12-29 16:11:00')
from dim.city
limit 1;
输出结果:'2012-12-29'
4.datediff(string enddate, string startdate)
说明:结束时间减去开始时间的天数
eg:select
datediff('2012-12-29 10:00:00', '2012-12-28 23:00:00'),
输出结果:1
5.date_add(string startdate, int days)
说明:日期相加操作
eg:select
date_add('2012-12-29 10:00:00', 1),
输出结果:‘2012-12-30’
6.date_sub (string startdate, int days)
说明:日期相减操作
eg:date_sub('2012-12-29', 1)
输出结果:‘2012-12-28’
7.date2datekey/datekey2date
说明:date类型与datekey类型转换函数
eg:select
date2datekey('2012-12-29'),
datekey2date(20121229)
from dim.city
limit 1;
输出结果:20121229, '2012-12-29'
8.year(string date)
month (string date)
day (string date)
hour (string date)
minute (string date)
second (string date)
weekofyear (string date)
说明:取时间的年月日时分秒以及时间是在今年的多少周,这个就不举例子了。
Hive中有类似Mysql的now()变量吗?
mysql有一个now()函数可以取到当前的时间,hive中我们可以使用 unix_timestamp() 函数来替代。
比如 from_unixtime(unix_timestamp()) 即可取到当前时间了,当前日期用to_date(from_unixtime(unix_timestamp()))
日期该怎么比较大小?
如上文,hive没有专门的日期类型,故大小比较的话直接转换成相应的类型比较。
以字符串存储的话则采用字符串的比较方式,以整数存储的话则采用整数的比较方式,但是不能将字符串跟整数进行比较。