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';这些查询将返回截断到指定单位的日期或时间戳。