【问题标题】:PostgreSQL new Date FormatPostgreSQL 新日期格式
【发布时间】:2018-07-18 10:08:11
【问题描述】:

我正在尝试将我的日期列从“YYYY-MM-DD”格式化为“YYYYMM”。

我的代码: SELECT to_char(日期'2015-06-01', 'YYYYMM');

我不确定这是否有效,因为日期看起来仍然像原始格式。此外,新的“YYYYMM”格式是否会应用于此表中导入的数据?

【问题讨论】:

  • 请详细说明您的问题
  • 看看postgresql documentation 供您参考。
  • 转换为字符、子字符串等
  • 不,数据将保持正确的内部格式。

标签: sql database postgresql format


【解决方案1】:

date 类型被实现为从 2000-01-01 开始的天数 - 这个数字没有任何视觉形式 - 它只是偏移量。您可以更改数据可视化时使用的可视化。

postgres=# set datestyle to ISO;
postgres=# select current_date;
┌────────────┐
│    date    │
╞════════════╡
│ 2015-11-11 │
└────────────┘
(1 row)

postgres=# set datestyle to GERMAN;
postgres=# select current_date;
┌────────────┐
│    date    │
╞════════════╡
│ 11.11.2015 │
└────────────┘
(1 row)

还有其他辅助函数用于格式化日期to_char和处理日期字符串to_datedatestyle 可用的样式集是有限的。更多 datestyle 是全局变量,使用它会增加应用程序中出现意外缺陷的风险 - 因此不建议使用 datestyle

postgres=# select to_char(current_date, 'YYYYMM');
┌─────────┐
│ to_char │
╞═════════╡
│ 201511  │
└─────────┘
(1 row)
set datestyle to iso;
postgres=# select to_date('201511','YYYYMM');
┌────────────┐
│  to_date   │
╞════════════╡
│ 2015-11-01 │
└────────────┘
(1 row)

默认情况下,数据以文本格式从 Postgres 传送到客户端。因此,这些格式化函数(功能)的使用会对客户端接收到的数据(来自数据库)产生影响。 to_char 会显式转换为文本类型,因此任何客户端都可以读取它(因为它必须能够读取文本)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2017-10-01
    相关资源
    最近更新 更多