Hive中日期与时间戳的转换

什么是时间戳?

时间戳是指**格林尼治时间**1970年01月01日00时00分00秒(北京时间1970年01月01日时00分00秒)起至现在的总秒数。

注意:不管你在地球上的任何地方,这一时刻的时间戳是相同的。但是!同一个时间戳在不同的时区会表示不同的时间。比如在集群上通过hive函数转换的是北京时间,但是在本地python转换就成了美国的时间。可能是根据配置不同?(猜),但是在数据处理过程中一定要看清楚。(2017.11.21添加)

时间戳=>指定格式的日期

# timestamp是时间戳
# 如果timestamp原先是毫秒,则我们/1000后,会自动转换成double类型,但是主要from_unixtime要求第一个参数需要为bigint类型,所以我们需要用cast进行类型转换。
# 语法from_unixtime(bigint unixtime[, stringformat])
select from_unixtime(timestamp, 'yyyy-MM-dd HH:mm:ss') from test_table

指定格式日期=>时间戳

# 如果不写第二个参数,默认格式是 yyyy-MM-dd HH:mm:ss
select unix_timestamp('20170101 13:20:30', 'yyyyMMdd HH:mm:ss') from test_table

时间=>日期

# 只能接受这种形式
select to_date('2017-01-01 13:20:30') from test_table

日期=>年/月/日/时/分/秒

# year(), month(), day(), hour(), minute(), second()
# week() 返回日期所在的星期数
select year('2017-01-01 13:20:30') from test_table

日期比较

# 返回结束日期减去开始日期的天数
# 语法:datediff(string enddate, string startdate)
select datediff('2017-01-31', '2017-01-1') from test_table

日期加减

# 语法:date_add(string startdate, int days)
select date_add('2017-01-01', 10) from test_table
select date_sub('2017-01-01', 10) from test_table

猜你喜欢

转载自blog.csdn.net/wj1066/article/details/78795887