在jsonb中存储时间戳时,我意识到将current\u timestamp和now()放入jsonb时使用的格式不同于我直接使用它们时使用的格式.这是怎么回事?虽然两者都是ISO8601格式,但我更希望它们都使用相同的格式.为什么会有两种不同的违约?

select version();
select now();
select current_timestamp;
select jsonb_build_object('timestamptz', current_timestamp);
select jsonb_build_object('timestamptz', now());
| version                                                                                                |
| :----------------------------------------------------------------------------------------------------- |
| PostgreSQL 12.9 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 8.5.0 20210514 (Red Hat 8.5.0-4), 64-bit |

| now                           |
| :---------------------------- |
| 2022-07-14 14:13:42.696612+01 |

| current_timestamp             |
| :---------------------------- |
| 2022-07-14 14:13:42.696612+01 |

| jsonb_build_object                                  |
| :-------------------------------------------------- |
| {"timestamptz": "2022-07-14T14:13:42.696612+01:00"} |

| jsonb_build_object                                  |
| :-------------------------------------------------- |
| {"timestamptz": "2022-07-14T14:13:42.696612+01:00"} |

db<>fiddle 100

推荐答案

ISO/IEC 9075-2:2016(SQL:2016)第5.3节定义了时间戳文字的格式(扩展为时间戳到字符串的默认转换);文字(&T);要在日期和时间之间使用空格作为分隔符:

<timestamp literal> ::=
  TIMESTAMP <timestamp string>

<timestamp string> ::=
  <quote> <unquoted timestamp string> <quote>

<unquoted timestamp string> ::=
  <unquoted date string> <space> <unquoted time string>

<unquoted date string><unquoted time string>均遵循ISO-8601的格式.

因此,为了符合标准、互操作性和向后兼容性,必须在SQL本身中使用这种格式.

很可能,当PostgreSQL添加JSON时,SQL标准的这一历史包袱被忽略了,取而代之的是ISO-8601,因为许多其他JSON序列化解决方案也使用了ISO-8601,这导致使用T作为分隔符.

Postgresql相关问答推荐

此PostgreSQL汇总分组不适用于窗口表达式

Select 所有数组类型和维度

Docker化的PostgreSQL:FATAL:用户&postgres的密码身份验证失败

可以向判断枚举值的SQL列添加约束吗?

为什么 Postgres 中的 now() 和 now()::timestamp 对于 CET 和 CEST 时区如此错误?

为什么我的唯一索引在 Postgresql 中不起作用?

使用 OpenCypher 和 Apache AGE 在两个顶点之间创建双向关系

在 postgresql 数据库 timestampz 中保留用户偏移量

Windows上的psql:错误:编码UTF8的字节序列无效:0xc8 0x20

有没有办法使用postgresql将具有不同ID的同一行多次添加到表中?

PostgreSQL:如何避免被零除?

如何将 grafana 与 Google Cloud SQL 集成

我应该使用哪个 postgresql 包?

是否可以在 Postgres 中存储一个 1 字节的数字?

从 PostgreSQL 中的数字获取月份名称

查询仅属于特定部门的用户

丢弃顺序和级联

如何使用 Node.js 和 Postgresql 找到最后一个插入 ID?

使用枚举与布尔值?

使用 SQLAlchemy 进行 PostgreSQL ILIKE 查询