從 PostgreSQL 中的 datetime 列中提取日期、小時、分鐘等資訊
讓我們建立一個包含一個時間戳列的新表-
CREATE TABLE timestamp_test( ts timestamp );
現在讓我們用一些資料填充它-
INSERT INTO timestamp_test(ts) VALUES(current_timestamp), (current_timestamp+interval '5 days'), (current_timestamp-interval '18 hours'), (current_timestamp+interval '1 year'), (current_timestamp+interval '3 minutes'), (current_timestamp-interval '6 years');
如果您查詢該表 (SELECT * from timestamp_test),您將看到以下輸出 -
| ts |
|---|
| 2021-01-30 19:23:24.008087 |
| 2021-02-04 19:23:24.008087 |
| 2021-01-30 01:23:24.008087 |
| 2022-01-30 19:23:24.008087 |
| 2021-01-30 19:26:24.008087 |
| 2015-01-30 19:23:24.008087 |
現在,為了從時間戳列中提取小時、分鐘等資訊,我們使用 EXTRACT 函式。以下是幾個示例-
SELECT EXTRACT(HOUR from ts) as hour from timestamp_test
輸出 -
| hour |
|---|
| 19 |
| 19 |
| 1 |
| 19 |
| 19 |
| 19 |
類似地 -
SELECT EXTRACT(MONTH from ts) as month from timestamp_test
| month |
|---|
| 1 |
| 2 |
| 1 |
| 1 |
| 1 |
| 1 |
您還可以提取不太明顯的值,例如 ISO 周或世紀 -
SELECT EXTRACT(CENTURY from ts) as century, EXTRACT(WEEK from ts) as week from timestamp_test
| century | week |
|---|---|
| 21 | 4 |
| 21 | 5 |
| 21 | 4 |
| 21 | 4 |
| 21 | 4 |
| 21 | 5 |
要獲取您可以從時間戳列中提取的完整值列表,請參閱 https://postgres.tw/docs/9.1/functions-datetime.html
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP