JQ - 使用非 UTC 日期字段并回顾一定时间量

问题描述 投票:0回答:1

我正在尝试编写一个 BASH+jq 单行代码,只返回不到 5 分钟的条目,因为我正在编写自动化,只回顾 5 分钟(BASH)。使用以下 JSON:

[
  {
    "id": 621024,
    "iid": 99999,
    "project_id": 999,
    "sha": "faf897sd98fa987afsd98f7",
    "ref": "master",
    "status": "running",
    "source": "push",
    "created_at": "2024-05-10T16:32:01.072-04:00",
    "updated_at": "2024-05-10T16:32:03.565-04:00",
    "web_url": "https://gitlab/pipelines/9999",
    "name": null
  },
  {
    "id": 621023,
    "iid": 99999,
    "project_id": 999,
    "sha": "faf897sd98fa987afsd98f7",
    "ref": "master",
    "status": "success",
    "source": "push",
    "created_at": "2024-05-10T16:31:47.951-04:00",
    "updated_at": "2024-05-10T16:35:30.362-04:00",
    "web_url": "https://gitlab/pipelines/9999",
    "name": null
  },
  {
    "id": 621020,
    "iid": 99999,
    "project_id": 999,
    "sha": "faf897sd98fa987afsd98f7",
    "ref": "master",
    "status": "waiting_for_resource",
    "source": "push",
    "created_at": "2024-05-10T15:27:00.248-04:00",
    "updated_at": "2024-05-10T15:30:14.172-04:00",
    "web_url": "https://gitlab/pipelines/9999",
    "name": null
  },
  {
    "id": 621019,
    "iid": 99999,
    "project_id": 999,
    "sha": "faf897sd98fa987afsd98f7",
    "ref": "master",
    "status": "success",
    "source": "push",
    "created_at": "2024-05-10T14:26:02.235-04:00",
    "updated_at": "2024-05-10T14:29:45.406-04:00",
    "web_url": "https://gitlab/pipelines/9999",
    "name": null
  }
]

我的挑战是

created_at
返回的日期是美国东部时间

我一直在尝试将一些传统的时间函数/工具与 jq 一起使用,但认为它不起作用,因为他们希望检查的日期是 UTC

我知道我可以使用类似的方法来减少毫秒数

jq  '.[] | .created_at |= .[0:19]'

但这仍然给我留下了 EST 的时间戳。

"created_at": "2024-05-10T15:27:00"

我阅读的所有文档都谈到需要 ISO 8601 中的日期才能使用某些日期/时间函数进行解析。我不知道要添加什么到我的 jq 中,这样只会减去选择不到 5 分钟的条目

此查询失败:

jq  '.[] | .created_at |= .[0:19] | select(.created_at | fromdate - 300)'

有错误

jq: error (at <stdin>:55): date "2024-05-10T16:32:01" does not match format "%Y-%m-%dT%H:%M:%SZ"

json jq
1个回答
0
投票

要么使用jqGo实现,它可以正确解析

%z

gojq '
  map(select(
    .created_at | sub("\\.[0-9]+"; "")
    | strptime("%FT%T%z") | now - mktime <= 300
  ))
'

或者手动解释(数字)时区(如

(+|-)HH[:]MM
),并进行数学计算:

map(select(
  .created_at | sub("\\.[0-9]+"; "")
  | ( capture(".{19}(?<d>[+-])(?<h>[0-9]{2}):?(?<m>[0-9]{2})")
      | .d += "1" | .[] |= tonumber
    ) as $tz
  | strptime("%FT%T%z") | .[3] -= $tz.d * $tz.h | .[4] -= $tz.d * $tz.m
  | now - mktime <= 300
))
© www.soinside.com 2019 - 2024. All rights reserved.