从 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://postgresql.ac.cn/docs/9.1/functions-datetime.html
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP