postgre SQL 中的時間類型
有4種:
timestamp (時間類型 格式 : ‘YYYY-MM-DD HH24:MI:SS’)
date (日期 格式: ‘YYYY-MM-DD’)
time (時間 格式: ‘HH24:MI:SS’)
interval (間隔 格式: day hour hours second )
時間進行計算時:
同類型的計算,結果為 interval 格式
不同類型計算要用大範圍的時間類型減去小範圍的時間類型,結果的類型不固定
注意 :
時間類型不是函數 不需要括號 ,注意寫法
時間類型相關SQL:
1,date類型 與 integer計算,integer不帶單位,單位默認為date的最小單位
select * from labnor where day = ‘2020-01-08’ and add_date > date ‘2020-01-07’ + integer ‘2’
date類型 與 interval 計算,interval 要指定類型 ,不指定是默認為hour
select * from abnormal where day = ‘2020-01-08’ and add_date > date ‘2020-01-07’ - interval ‘1 hour’
2,時間計算
大範圍的時間-小範圍的時間
select timestamp ‘2020-02-02 12:12:12’ -date ‘2020-02-01’
select date ‘2020-02-02’ - time ‘12:00:00’
select date ‘2020-01-07’ - interval ‘1 second’
select date ‘2001-09-28’ + integer ‘7’ > date ‘2001-09-28’ + time ‘03:00’
select date ‘2001-09-28’ + time ‘03:00’
select date ‘2020-01-07’ + integer ‘2’
3,時間類型與其他類型的轉換函數
select to_date(‘05 Dec 2000’, ‘DD Mon YYYY’) --字符串轉日期 ,日期轉時間間隔沒有意義,所以沒有此方法
select to_char(current_timestamp, ‘HH12:MI:SS’) --把時間戳轉換成字符串
select to_timestamp(1284352323) --時間戳轉時間
select to_timestamp(‘05 Dec 2000’, 'DD Mon YYYY ') --將時間轉化成指定的格式
select to_timestamp(‘2001-09-28 12:12:12’, ‘YYYY-MM-DD HH24:MI:SS’)
select current_timestamp
select current_time