jq日期和unix时间戳 [英] jq dates and unix timestamps

查看:61
本文介绍了jq日期和unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个带有unix时间戳值(以毫秒为单位)的数据.像这样:

So I have a data with bunch of unix timestamp values (in milliseconds). Something like this:

{
    "id": "f6922fd5-4f97-4113-820e-b45eba0ae236",
    "published_at": 1461624333859,
    "tracking_id": "a85d5ed5-5efa-461b-aae0-beb2098c0ff7",
}, {
    "id": "835d412f-5162-440c-937b-7276f22c4eb9",
    "published_at": 1461625249934,
    "tracking_id": "86472ba2-ce5f-400f-b42a-5a0ac155c42c",
}, {
    "id": "bc2efcac-67a0-4855-856a-f31ce5e4618e",
    "published_at": 1461625253393,
    "tracking_id": "c005398f-07f8-4a37-b96d-9ab019d586c2",
}

很多时候,我们需要搜索特定日期内的行.是否可以用jq查询,提供人类可读的日期,例如2016-04-25.我也想知道是否有其他方法可以使jq以人类可读的形式显示published_at值?

And very often we need to search for rows within a certain date. Is it possible to query with jq, providing human readable dates e.g. 2016-04-25. Also I wonder if the other way around possible, to make jq show published_at values in human readable form?

例如,这可行:

$ echo 1461624333 | jq 'todate'   
"2016-04-25T22:45:33Z"

尽管必须以秒为单位,而不是毫秒

although it has to be in seconds, not milliseconds

推荐答案

当然!您提供的输入不是有效的JSON,但是我将假定删除了这些对象上的结尾逗号,并将这些对象包装在一个数组中,该数组将成为JSON文档的根对象.

Sure! Your provided input is not valid JSON, but I'm going to assume the trailing commas on those objects are removed and the objects are wrapped in an array, which would be the root object of the JSON document.

首先,我们可以将毫秒精度的UNIX日期转换为秒精度,这是jq的日期函数所期望的,然后将其转换为您期望的人类可读日期:

First, we can transform the millisecond-precision UNIX dates into second-precision, which is what jq's date functions expect, and then convert that to the human-readable dates you expect:

.[].published_at |= (. / 1000 | strftime("%Y-%m-%d"))

然后,我们仅选择日期匹配的那些元素:

Then, we select only those elements whose dates match:

map(select(.published_at == $date))

最后,我们将所有内容组合在一起,从命令行获取$date变量:

Lastly, we put it all together, taking the $date variable from the command-line:

jq --arg date "2016-04-25" '.[].published_at |= (. / 1000 | strftime("%Y-%m-%d")) | map(select(.published_at == $date))' stuff.json

这篇关于jq日期和unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆