windows - 比较windows jq中的 'YYYY-mm-dd HH:MM:SS'格式时间戳

标签 windows cmd jq

我在 Ubuntu 上使用 jq,但现在我必须将命令移植到 Windows 8.1。我正在使用 jq 1.6。

但是我在 Windows jq 上使用 strptime 时遇到此错误。

jq: error (at xxxx.json:xxx): strptime/1 not implemented on this platform

Windows 的 strptime 还有哪些其他选项?

示例:

这对我来说适用于 Ubuntu,并且需要使其适用于 Windows(只需要以秒为单位的时间差)。

jq -n '{"t1": "2018-06-01 12:45:56", "t2": "2018-06-03 22:10:01"} |
       (.t2 | strptime("%Y-%m-%d %H:%M:%S") | mktime)-
       (.t1 | strptime("%Y-%m-%d %H:%M:%S") | mktime)'
206645

更新:

我刚刚发现即使是 mktime 在 Windows 上也会产生同样的错误。所以我更新了问题,我只需要某种方法来比较以秒为单位的特定格式的日期时间(使用或不使用strptime)。

最佳答案

首先,jq 的 mktime/0 的“插件”实现:

# [1970,  0,  1,  0,  0,  0] | mktime #=> 0
# For Jan, use 0 for $m.
# Emit null if any inputs are judged to be invalid.
# No attempt to account for leap seconds is made.
# Can also be used for earlier years.
#
# Adapted from
# https://codereview.stackexchange.com/questions/11614/determine-total-number-of-seconds-since-the-epoch
def mktime:
  def max: if .[0] > .[1] then .[0] else .[1] end;
  def min: if .[0] > .[1] then .[1] else .[0] end; 
  def NDaysInMonth: [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  . as [$y,  $m,  $d,  $h,  $mn,  $s]
  | if ($y < 0 or $m < 0 or $d < 1 or $h < 0 or $mn < 0 or $s < 0)
    then null
    else
    1970 as $ye # UNIX epoch 01/01/1970
    | (if $y > $ye then 1 else -1 end) as $sign
    | ([$y, $ye] | max) as $maxY
    | ([$y, $ye] | min) as $minY
    | reduce range($minY; $maxY) as $i ({nleapYears: 0};
        if (($i % 100 != 0 and $i % 4 == 0) or $i % 400 == 0) then .nleapYears += 1 else . end)
    | if ($m > 1) and (($y % 100 != 0 and $y % 4 == 0) or $y % 400 == 0)
      then .nleapYears += $sign
      else .
      end
    | .nleapYears |= ([0, .] | max)
    | reduce range(0;$m) as $i (.monthsNDays = 0;
        .monthsNDays += NDaysInMonth[$i])
    | (($y - $ye) * 365 + $sign * .nleapYears + .monthsNDays + $d - 1) * 86400
        + $h * 3600 + $mn * 60 + $s
    end ;

接下来,要解析 "2018-06-01 12:45:56" 形式的日期字符串,您可以轻松使用 jq 的 capture (请参阅 jq manual ) 。由于 SO 不是免费的编程服务,因此将其作为练习,就像将所有部分组合在一起一样。

关于windows - 比较windows jq中的 'YYYY-mm-dd HH:MM:SS'格式时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53409620/

相关文章:

python - 从 python 重启本地计算机

python - 转换代码以在windows中读取文件到linux

c++ - system() 到 c++ 而不调用 cmd.exe

json - 通过 jq 为每个 JSON 项运行 bash 命令

json - 如何解析 JSON 输入

php - 在CMD中查找文件位置并使用它

c - 使用 c 的对象树?

java - 从命令提示符显示 java 程序的输出并将其复制到文件中

python - 将特殊字符传递给 cmd.exe 中的 python 脚本

json - 遍历json以使用jq删除null字段