什麼是時間戳?
時間戳是指**格林尼治時間**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