date_trunc
函數(shù)用于在 PostgreSQL 中將日期或時間戳值截斷(向下取整)到指定的精度級別。當您想要忽略較小的時間單位(例如,小時、分鐘、秒),專注于較大的單位(例如,天、月、年)時,該函數(shù)非常有用。date_trunc
的語法如下:
date_trunc(unit, source);
文章來源:http://www.zghlxwxcb.cn/news/detail-798024.html
-
unit
:指定要將源值截斷到的時間單位??梢允且韵轮唬?-
'microseconds'
(微秒) -
'milliseconds'
(毫秒) -
'second'
或'seconds'
(秒) -
'minute'
或'minutes'
(分鐘) -
'hour'
或'hours'
(小時) -
'day'
或'days'
(天) -
'week'
或'weeks'
(周) -
'month'
或'months'
(月) -
'quarter'
或'quarters'
(季度) -
'year'
或'years'
(年)
-
通過指定 unit
,您可以將 source
的值截斷到所需的時間精度。以下是一些示例:文章來源地址http://www.zghlxwxcb.cn/news/detail-798024.html
-- 將時間戳截斷到分鐘
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';
這些查詢將返回截斷到指定單位的日期或時間戳。
到了這里,關于【PGSQL】date_trunc 函數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!