最近做一些統計相關的需求,用到了一些時間計算,總結一下。
1、獲取時間戳
select extract(epoch from current_timestamp) 或 select date_part('epoch', current_timestamp),current_timestamp可以用now()替代。
2、時間戳轉回成 timestamp
select to_timestamp('1618463700')
3、類型格式化
select to_char(current_timestamp, 'HH24:MI:SS')
4、時間截取
select date_trunc('month', current_timestamp) 注意:小於選擇的精度都會設置成0或1,比如例子獲取到的是當前時間所在月份的第一天。用戶獲取某個精度下的起始時間。
5、獲取子域
select date_part('month', timestamp '2021-04-15 13:40:22')') 結果:4
6、計算時間差
select age(timestamp '2021-04-15 13:40',timestamp '2021-03-12 08:12') 結果:1 mon 3 days 05:28:00 注意:age獲取的月域可能有歧義,因為不同的月份有不同的天數
select timestamptz '2021-04-15 13:40' - timestamptz '2021-03-12 08:12' 結果:34 days 05:28:00
select extract(epoch from timestamptz '2021-04-15 13:40' - timestamptz '2021-03-12 08:12') 結果:2957280 單位:s
或者
select date_part('epoch', timestamptz '2021-04-15 13:40' - timestamptz '2021-03-12 08:12') 結果:2957280 單位:s
官方文檔:
http://postgres.cn/docs/11/functions-datetime.html
http://postgres.cn/docs/11/functions-formatting.html
