json jq 日期和 unix 时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36853202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jq dates and unix timestamps
提问by iLemming
So I have a data with bunch of unix timestamp values (in milliseconds). Something like this:
所以我有一个带有一堆 unix 时间戳值(以毫秒为单位)的数据。像这样的东西:
{
"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",
}
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_atvalues in human readable form?
我们经常需要搜索某个日期内的行。是否可以使用 jq 进行查询,提供人类可读的日期,例如2016-04-25. 另外我想知道是否可能以另一种方式使 jqpublished_at以人类可读的形式显示值?
For example this works:
例如这有效:
$ echo 1461624333 | jq 'todate'
"2016-04-25T22:45:33Z"
although it has to be in seconds, not milliseconds
虽然它必须以秒为单位,而不是毫秒
回答by
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.
当然!您提供的输入不是有效的 JSON,但我将假设这些对象上的尾随逗号已被删除,并且这些对象被包装在一个数组中,这将是 JSON 文档的根对象。
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:
首先,我们可以将毫秒精度的 UNIX 日期转换为秒精度,这是 jq 的日期函数所期望的,然后将其转换为您期望的人类可读的日期:
.[].published_at |= (. / 1000 | strftime("%Y-%m-%d"))
Then, we select only those elements whose dates match:
然后,我们只选择日期匹配的元素:
map(select(.published_at == $date))
Lastly, we put it all together, taking the $datevariable from the command-line:
最后,我们把它们放在一起,$date从命令行获取变量:
jq --arg date "2016-04-25" '.[].published_at |= (. / 1000 | strftime("%Y-%m-%d")) | map(select(.published_at == $date))' stuff.json
回答by peak
jq 1.5 has standard time-and-date functions such as strftime, as documented in the online manual. However support for TZ is extremely limited and/or unreliable, as illustrated here:
jq 1.5 具有标准的时间和日期功能,例如 strftime,如在线手册中所述。然而,对 TZ 的支持极其有限和/或不可靠,如下所示:
$ echo $TZ
$ jq -n '123 | strftime("%B %d %Y %I:%M%p %Z")'
"January 01 1970 12:02AM EST"
TZ='Asia/Kolkata' jq -n '123 | strftime("%B %d %Y %I:%M%p %Z")'
"January 01 1970 12:02AM IST"
strflocaltime
本地时间
If your jq has strflocaltime:
如果您的 jq 有strflocaltime:
TZ=Asia/Kolkata jq -n '123|strflocaltime("%Y-%m-%dT%H:%M:%S %Z")'
"1970-01-01T05:32:03 IST"

