PostgreSQL常用时间函数与时间计算提取示例说明

常用函数与常量

函数 说明
current_time 现在的时间
current_date 今天的日期
current_timestamp 当前日期和时间
now() 当前的日期和时间和current_timestamp一样
localtime time,当前时间
localtimestamp 当前日期和时间
timeofday() 字符串,当前日期和时间
age(timestamp1, timestamp2) 计算年纪,timestamp1-timestamp2,结果类型是interval,类似于:29 years 9 mons 27 days
select current_date,current_time,current_timestamp,now(),localtime,localtimestamp,timeofday();

PostgreSQL常用时间变量

select age('2030-04-10', '2000-06-13');

第1个参数减第2个参数,age返回值是interval,很方便算年龄

PostgreSQL age函数

-- 时间戳转字符串再截取
SELECT now()::timestamp,substring(''||now()::timestamp from 1 for 19);

PostgreSQL时间截取

to_timestamp(字符串转时间戳、数字转时间戳)

函数 说明
to_timestamp(text, text) 把字串转换成时间戳
to_timestamp(double) 把数字转时间戳
select to_timestamp(1859351600),to_timestamp('1859351600'::bigint),to_timestamp('2090 01 12', 'YYYY MM DD');

PostgreSQL转时间戳

想要了解YYYY MM DD代表什么,可以参考后文:日期时间格式化字符串

date与to_date(字符串转日期、时间戳转日期)

函数 说明
to_date(text, text) 字串转日期,第1个参数是时间,第2个参数是格式化字符串
date(timestamp) 时间戳转日期
date(text) 字符串转日期
select to_date('2090 01 12', 'YYYY MM DD'),date(now()),date('2090-09-28');

PostgreSQL to_date函数

在一些喜欢用字符串存时间的计算时非常有用,虽然不推荐在数据库上做计算,但是有时候有些特殊的项目,需要存储过程,这些函数能极大的简化计算。

例如,有些每日都要和前一日比(这里简化了只计算了日期):

select priceday,to_char(to_date(priceday, 'YYYYMMDD')-interval '1 day','YYYYmmdd') as lastDay from elt_data_table;

interval(时间计算)

interval还是非常有用,不仅仅可以用来表示时间差,还可以用来做时间计算。

基本操作与格式

操作符 说明
year
month
day
hour 小时
min 分钟
sec

加不加s不影响,interval '2 day’和interval '2 days’都可以。


select now(),now() - interval '1 day' as subday,
now<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值