PostgreSQL中date_trunc函数的语法及一些示例
作者:Holen&&Beer
这篇文章主要给大家介绍了关于PostgreSQL中date_trunc函数的语法及一些示例的相关资料,DATE_TRUNC函数是PostgreSQL数据库中用于截断日期部分的函数,文中通过代码介绍的非常详细,需要的朋友可以参考下
date_trunc 函数用于在 PostgreSQL 中将日期或时间戳值截断(向下取整)到指定的精度级别。当您想要忽略较小的时间单位(例如,小时、分钟、秒),专注于较大的单位(例如,天、月、年)时,该函数非常有用。date_trunc 的语法如下:
date_trunc(unit, source);
unit:指定要将源值截断到的时间单位。可以是以下之一:'microseconds'(微秒)'milliseconds'(毫秒)'second'或'seconds'(秒)'minute'或'minutes'(分钟)'hour'或'hours'(小时)'day'或'days'(天)'week'或'weeks'(周)'month'或'months'(月)'quarter'或'quarters'(季度)'year'或'years'(年)
通过指定 unit,您可以将 source 的值截断到所需的时间精度。以下是一些示例:
-- 将时间戳截断到分钟
SELECT date_trunc('minute', current_timestamp);
-- 2024-01-17 08:08:00
--
-- 将时间戳截断到小时
SELECT date_trunc('hour', current_timestamp);
-- 2024-01-17 08:00:00
--
-- 将时间戳截断到天
SELECT date_trunc('day', current_timestamp);
-- 2024-01-17 00:00:00
--
-- 将时间戳截断到月
SELECT date_trunc('month', TIMESTAMP '2024-02-16 14:32:45');
-- 2024-02-01 00:00:00
--
-- 将时间戳截断到年
SELECT date_trunc('year', TIMESTAMP '2024-02-16 14:32:45');
-- 2024-01-01 00:00:00
--
-- 一天开始
SELECT date_trunc('day', current_timestamp);
--
-- 一天结束
SELECT date_trunc('day', current_timestamp) + INTERVAL '1 day' - interval '1 second';
这些查询将返回截断到指定单位的日期或时间戳。补充:
me=# select date_trunc('day',date '2018-05-15 09:00:00+08') + interval '9 h';
?column?
------------------------
2018-05-15 09:00:00+08
(1 行记录)
me=# select date_trunc('day',date '2018-05-15 14:09:04.127444+08') + interval '9 h';
?column?
------------------------
2018-05-15 09:00:00+08
(1 行记录)
me=# select date_trunc('day',date '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
------------------------
2018-05-14 09:00:00+08
(1 行记录)
me=# select date_trunc('day',time '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
----------
09:00:00
(1 行记录)
me=# select date_trunc('day',timestamp '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
---------------------
2018-05-14 09:00:00
(1 行记录)
me=# select date_trunc('day',timestamptz '2018-05-14 14:09:04.127444+08') + interval '9 h';
?column?
------------------------
2018-05-14 09:00:00+08
(1 行记录)
me=# select date_trunc('day',timestamptz '2018-05-14 14:09:04.127444+08'+ interval '9 h');
date_trunc
------------------------
2018-05-14 00:00:00+08
(1 行记录)
总结
到此这篇关于PostgreSQL中date_trunc函数的语法及一些示例的文章就介绍到这了,更多相关PGSQL date_trunc函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
