在jq输出中将12h时间值格式化为24h

时间:2019-01-02 12:40:12

标签: json jq datetime-format

我从jQuery获得的json中具有“ h:mm AM” /“ h:mm PM”格式的值。 有没有办法解析这些12h格式的值并将其转换为24h的值?

样本输入:

{ "times": [ [ "8:16 AM", "EventA" ], [ "3:19 PM", "EventB" ] ]}

所需的输出:

{ "times": [ [ "8:16", "EventA" ], [ "15:19", "EventB" ] ]}

3 个答案:

答案 0 :(得分:1)

以下内容比此处实际所需的内容更为通用:

def to24h:
    (capture("(?<pre>.*)(?<h>[01][0-9])(?<m>:[0-5][0-9]) *(?<midi>[aApP])[mM](?<post>.*)") //
     capture("(?<pre>.*)(?<h>[0-9])(?<m>:[0-5][0-9]) *(?<midi>[aApP])[mM](?<post>.*)"))

  | (.midi|ascii_upcase) as $midi
  | .pre + (if $midi == "A" then .h else "\(12+(.h|tonumber))" end) + .m + .post ;

使用此def,您可以使用过滤器转换给定的输入:

.times |= map( map(to24h // .) )

或者如果您想检查所有字符串:

walk( if type=="string" then to24h // . else . end)

答案 1 :(得分:0)

我们可以使用jq的日期函数吗?

jq '(.times[] | .[])
    |= ( if test("^\\d{1,2}:\\d{1,2} [AP]M$"; "i")
         then ( strptime("%H:%M %p") | strftime("%k:%M") | sub("^ "; "") )
         else . end ) '

答案 2 :(得分:0)

每次使用strptimestrftime进行解析和重新格式化。

% jq -c '.times[][0] |= (strptime("%H:%M %p") | strftime("%H:%M"))'
{ "times": [ [ "8:16 AM", "EventA" ], [ "3:19 PM", "EventB" ] ]}
{"times":[["08:16","EventA"],["15:19","EventB"]]}
^C

strptime生成一个列表,其中基于%H匹配的修饰符将%p匹配的小时数调整为24小时制; strftime然后简单地输出任何小时。

困难的部分不是转换;它确定应该将转换应用于的值。在这里,我们假设每次都是times键的数组值中数组的第一个元素。

相关问题