在PostgreSQL中可以直接对时间进行加减运算:、
SELECT now()::timestamp + '1 year'; --当前时间加1年
SELECT now()::timestamp + '1 month'; --当前时间加一个月
SELECT now()::timestamp + '1 day'; --当前时间加一天
SELECT now()::timestamp + '1 hour'; --当前时间加一个小时
SELECT now()::timestamp + '1 min'; --当前时间加一分钟
SELECT now()::timestamp + '1 sec'; --加一秒钟
select now()::timestamp + '1 year 1 month 1 day 1 hour 1 min 1 sec'; --加1年1月1天1时1分1秒
SELECT now()::timestamp + (col || ' day')::interval FROM table --把col字段转换成天 然后相加
取时间字段的部分值
在开发过程中,经常要取日期的年,月,日,小时等值,PostgreSQL 提供一个非常便利的EXTRACT函数。
--EXTRACT函数解释
EXTRACT(field FROM source): field 表示取的时间对象, source 表示取的日期来源,类型为 timestamp。
下面是一些例子。
--取年份
skytf=> select extract (year from now());
date_part
-----------
2011
(1 row)
--取月份
skytf=> select extract (month from now());
date_part
-----------
6
(1 row)
--取day
skytf=> select extract(day from now());
date_part
-----------
3
(1 row)
skytf=> select extract(day from timestamp '2011-06-03');
date_part
-----------
3
(1 row)
skytf=> select timestamp '2011-06-03';
timestamp
---------------------
2011-06-03 00:00:00
(1 row)
--取小时
skytf=> select extract (hour from now());
date_part
-----------
14
(1 row)
--取分钟
skytf=> select extract (minute from now());
date_part
-----------
59
(1 row)
--取秒
skytf=> select extract (second from now());
date_part
-----------
46.039333
(1 row)
--取所在哪个星期
skytf=> select extract (week from now());
date_part
-----------
22
(1 row)
RT:PostgreSQL数据库有两列,日期和年龄,如何一句话选出日期减去年龄后的日期。
PostgreqSQL中日期值可以和interval直接做加减运算。所以,只要把年龄转换成按年的interval值,就可以运算出结果了。示例:
1
2
3
4
|
select
dv, age, dv - (age ||
' year'
)::interval
as
nd
from
(
select
'2014-10-21'
::
date
as
dv, 2
as
age
) s;
|
查看今天是一年中的第几天
david=# select extract(doy from now()); date_part ----------- 102 (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=#