PostgreSQL 给定日期间隔初始时间计算

发布时间:2020-10-10 04:03:12 作者:pgmia
阅读:1341
开发者专用服务器限时活动,0元免费领! 查看>>

1.功能说明:

date_trunc: 截取给定时间(TIMESTAMP,date),获得指定精度(时,天,月,年)的初始使时间

2.一般时间

date_trunc('hour',TIMESTAMP '2018-08-16 20:38:40')

Result: 2018-08-16 20:00:00

date_trunc('day',TIMESTAMP '2018-08-16 20:38:40')

Result: 2018-08-16 00:00:00

date_trunc('month',TIMESTAMP '2018-08-16 20:38:40')

Result: 2018-08-01 00:00:00

date_trunc('year',TIMESTAMP '2018-08-16 20:38:40')

Result: 2018-01-01 00:00:00

3.特殊需求:

给定时间段的每年的所有月份的第一天,最后一天,下月第一天

-- Result: month_first_day, month_end_day, next_month

select date(zz) as month_first_day, date(zz + interval '1 month' - interval '1 day') as month_end_day, date(zz + interval '1 month') as next_month 

from generate_series(date_trunc('year',to_date('20180510','yyyymmdd')),date_trunc('year',to_date('201905','yyyymmdd')),'1 month') as tt(zz);

SQL结果:

 month_first_day | month_end_day | next_month 

-----------------+---------------+------------

 2018-01-01      | 2018-01-31    | 2018-02-01

 2018-02-01      | 2018-02-28    | 2018-03-01

 2018-03-01      | 2018-03-31    | 2018-04-01

 2018-04-01      | 2018-04-30    | 2018-05-01

 2018-05-01      | 2018-05-31    | 2018-06-01

 2018-06-01      | 2018-06-30    | 2018-07-01

 2018-07-01      | 2018-07-31    | 2018-08-01

 2018-08-01      | 2018-08-31    | 2018-09-01

 2018-09-01      | 2018-09-30    | 2018-10-01

 2018-10-01      | 2018-10-31    | 2018-11-01

 2018-11-01      | 2018-11-30    | 2018-12-01

 2018-12-01      | 2018-12-31    | 2019-01-01

 2019-01-01      | 2019-01-31    | 2019-02-01

(13 rows)

找出指定时间小时,天,月,年的初始值

-- Result: dtrunc_hour, dtrunc_day, dtrunc_month, dtrunc_year

SELECT date_trunc('hour', TIMESTAMP '2018-08-16 20:38:40') as dtrunc_hour ,date_trunc('day', TIMESTAMP '2018-08-16 20:38:40') as dtrunc_day,date_trunc('month', TIMESTAMP '2018-08-16 20:38:40') as dtrunc_month,date_trunc('year', TIMESTAMP '2018-08-16 20:38:40') as dtrunc_year;

SQL结果:

     dtrunc_hour     |     dtrunc_day      |    dtrunc_month     |     dtrunc_year     

---------------------+---------------------+---------------------+---------------------

 2018-08-16 20:00:00 | 2018-08-16 00:00:00 | 2018-08-01 00:00:00 | 2018-01-01 00:00:00

(1 row)

postgres=# 

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:
  1. postgresql——日期时间函数
  2. postgresql初始化失败怎么办

开发者交流群:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

postgresql timestamp gr st

上一篇:解决PyCharm不在run输出运行结果而不是再Console里输出的问题

下一篇:创建Azure Kubernetes(AKS)群集

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》
开发者交流群×