【问题标题】:how to calculate time duration from two date/time values using jq如何使用 jq 从两个日期/时间值计算持续时间
【发布时间】:2020-06-30 20:18:52
【问题描述】:

我有一些看起来像这样的 json....

[
  {
    "start": "20200629T202456Z",
    "end": "20200629T211459Z",
    "tags": [
      "WPP",
      "WPP review tasks, splashify popup",
      "clients",
      "work"
    ],
    "annotation": "update rules, fix drush errors, create base wpp-splash module."
  },
  {
    "start": "20200629T223000Z",
    "end": "20200629T224641Z",
    "tags": [
      "WPP",
      "WPP review tasks, splashify popup",
      "clients",
      "work"
    ]
  },
 ]

我想显示小时:分钟的持续时间,而不是“开始”和“结束”时间。

时间格式可能有点不寻常(?),它来自 timewarrior。我想如果日期/时间存储在普通的 unix 时间戳中,jq 会更容易完成,但也许这仍然是可能的? jq可以像这样写输出

[
  {
    "time": "0:50:03",
    "tags": [
      "WPP",
      "WPP review tasks, splashify popup",
      "clients",
      "work"
    ],
    "annotation": "update rules, fix drush errors, create base wpp-splash module."
  }
]

或类似的东西。

这可能吗?

【问题讨论】:

    标签: json datetime jq duration


    【解决方案1】:

    为了清楚起见,让我们定义一个辅助函数:

    def duration($finish; $start):
      def twodigits: "00" + tostring | .[-2:];
      [$finish, $start]
      | map(strptime("%Y%m%dT%H%M%SZ") | mktime) # seconds
      | .[0] - .[1]
      | (. % 60 | twodigits) as $s
      | (((. / 60) % 60) | twodigits)  as $m
      | (./3600 | floor) as $h
      | "\($h):\($m):\($s)" ;
    

    现在的解决方法很简单:

    map( {time: duration(.end;.start)} + del(.start,.end) )
    

    【讨论】:

    • 那是蟒蛇吗?还是 jq 允许定义辅助函数?我将如何在 linux 命令的管道中使用它?我需要把它放在一个可执行文件中吗?如何将我的 json 数据流传递给它?
    • 那是jq,它支持(嵌套)defs,但它们必须出现在main程序之前。如果有疑问,我建议您考虑使用 jq 的 -f 命令行选项,但在脚本(例如 bash 脚本)中,您可以很好地内联 jq 程序。我还建议您花时间在线浏览 jq 文档。
    • 你能举一个实现的例子吗?我以前从未使用 jq 编写过脚本,并且只在 timew export | jq 这样的简单管道中使用过它,并且不确定您提供的代码如何适合该工作流程。我正在努力挣扎……
    • 哦...所以如果我只是在一个 shell 脚本jq 'def duration...etc the rest of your code' 中执行此操作,我可以将 json 数据流通过管道传输到该 shell 脚本,所以现在它是 timew export | jq-tw-duration.sh。谢谢
    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 2021-11-28
    • 2016-12-31
    相关资源
    最近更新 更多