Postgres jsonb将记录集从UNIX转换为时间戳

时间:2018-03-25 06:14:07

标签: arrays postgresql timestamp sqldatatypes jsonb

我正在使用jsonb列的Postgres表。我已经能够创建一个记录集来将json转换为jsonb对象的行。我正在努力将timestamp从UNIX转换为可读的时间戳。

这是jsonb对象在将timestamp存储为UNIX时的样子:

{
  "signal": [
    {
      "id": "e80",
      "on": true,
      "unit": "sample 1",
      "timestamp": 1521505355
    },
    {
      "id": "97d",
      "on": false,
      "unit": "sample 2",
      "timestamp": 1521654433
    },
    {
      "id": "97d",
      "on": false,
      "unit": "sample 3",
      "timestamp": 1521654433
    }
  ]
}

理想情况下,我希望它看起来像这样但是timestamp

会出错
id | on   |  unit    | timestamp
---+------+----------+-------------------------- 
e80|true  | sample 1 | 2018-03-20 00:22:35+00:00
97d|false | sample 2 | 2018-03-21 17:47:13+00:00
97d|false | sample 3 | 2018-03-21 17:47:13+00:00

这是我到目前为止返回列的预期值但是为timestamp列提供错误

select b.*
from device d
cross join lateral jsonb_to_recordset(d.events->'signal') as 
    b("id" integer, "on" boolean, "unit" text, "timestamp" timestamp)

timestamp数据类型正在抛出错误。

[22008]错误:日期/时间字段值超出范围

非常感谢任何有关将timestamp从UNIX转换为实际时间戳的帮助或建议。

1 个答案:

答案 0 :(得分:1)

您可以在列定义列表中将其指定为INTEGER,然后使用TIMESTAMP将其转换为TO_TIMESTAMP

此外,您尝试定义的id不能是integer

SQL Fiddle

查询1

SELECT b.id
    ,b.ON
    ,b.unit
    ,to_timestamp("timestamp") AS "timestamp"
FROM device d
CROSS JOIN lateral jsonb_to_recordset(d.events -> 'signal')
AS b("id" TEXT, "on" boolean, "unit" TEXT, "timestamp" INT)

<强> Results

|  id |    on |     unit |            timestamp |
|-----|-------|----------|----------------------|
| e80 |  true | sample 1 | 2018-03-20T00:22:35Z |
| 97d | false | sample 2 | 2018-03-21T17:47:13Z |
| 97d | false | sample 3 | 2018-03-21T17:47:13Z |