相关文章推荐
冷静的课本  ·  AnalyticDB ...·  3 周前    · 
仗义的羽毛球  ·  PolarDBPostgreSQL版PL/S ...·  11 月前    · 
david=# select now() + interval '2 years';
           ?column?            
-------------------------------
 2015-04-12 15:49:03.168851+08
(1 row)
david=# select now() + interval '2 year'; 
           ?column?            
-------------------------------
 2015-04-12 15:49:12.378727+08
(1 row)
david=# select now() + interval '2 y';   
           ?column?           
------------------------------
 2015-04-12 15:49:25.46986+08
(1 row)
david=# select now() + interval '2 Y';
           ?column?            
-------------------------------
 2015-04-12 15:49:28.410853+08
(1 row)
david=# select now() + interval '2Y'; 
           ?column?            
-------------------------------
 2015-04-12 15:49:31.122831+08
(1 row)
david=# 

2.2 一个月后

david=# select now() + interval '1 month';  
           ?column?           
------------------------------
 2013-05-12 15:51:22.24373+08
(1 row)
david=# select now() + interval 'one month';
ERROR:  invalid input syntax for type interval: "one month"
LINE 1: select now() + interval 'one month';
david=# 

2.3 三周前

david=# select now() - interval '3 week';
           ?column?            
-------------------------------
 2013-03-22 16:00:04.203735+08
(1 row)
david=# 

2.4 十分钟后

david=# select now() + '10 min';                 
           ?column?            
-------------------------------
 2013-04-12 16:12:47.445744+08
(1 row)
david=# 

interval 可以不写,其值可以是:

Abbreviation Meaning Years Months (in the date part) Weeks Hours Minutes (in the time part) Seconds
david=# select age(now(), timestamp '1989-02-05');
----------------------------------------
 24 years 2 mons 7 days 17:05:49.119848
(1 row)
david=# 
david=# select age(timestamp '2007-09-15');       
------------------------
 5 years 6 mons 27 days
(1 row)
david=#

三、时间字段的截取

在开发过程中,经常要取日期的年,月,日,小时等值,PostgreSQL 提供一个非常便利的EXTRACT函数。

EXTRACT(field FROM source)

field 表示取的时间对象,source 表示取的日期来源,类型为 timestamp、time 或 interval。

3.1 取年份

david=# select extract(year from now());
 date_part 
-----------
(1 row)
david=# 

3.2 取月份

david=# select extract(month from now());    
 date_part 
-----------
(1 row)
david=# 
david=# select extract(day from timestamp '2013-04-13');
 date_part 
-----------
(1 row)
david=# 
david=# SELECT EXTRACT(DAY FROM INTERVAL '40 days 1 minute');
 date_part 
-----------
(1 row)
david=# 

3.3 查看今天是一年中的第几天

david=# select extract(doy from now());
 date_part 
-----------
(1 row)
david=# 

3.4 查看现在距 1970-01-01 00:00:00 UTC 的秒数

david=# select extract(epoch from now());
    date_part     
------------------
 1365755907.94474
(1 row)
david=# 

3.5 把epoch 值转换回时间戳

david=# SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 1369755555 * INTERVAL '1 second'; 
        ?column?        
------------------------
 2013-05-28 23:39:15+08
(1 row)
david=# 

以上是基本的PG时间/日期函数使用,可满足一般的开发运维应用。

详细用法请参考:

PostgreSQL官方说明: http://www.postgresql.org/docs/9.2/static/functions-datetime.html