shell 如何用jq将日期转换为毫秒

sshcrbum  于 2023-04-12  发布在  Shell
关注(0)|答案(1)|浏览(151)

在我的json文件file1.json中,我有一个毫秒的“horodate”字段:

{
    "horodate" : "2023-03-03T10:10:10.425Z"
}

我想在bash脚本中使用jq1.6将此日期转换为毫秒精度的时间戳:

{
    "horodate" : "1677838210425"
}

我试过这个:

jq '[.[] | .horodate |= (strptime("%Y-%m-%dT%H:%M:%S.%sZ")| mktime)]' file1.json > file2.json

或:

jq '[.[] | .horodate |= ( sub(".[0-9]+Z$"; "Z") | fromdate * 1000 + (.[20:23]|tonumber))]' file1.json > file2.json
bcs8qyzn

bcs8qyzn1#

# Input: ISO8601 time in the format specified by $fmt where 
# $fmt should end with "%SZ",
# and where the value of %S may include milliseconds.
# Output: milliseconds since the Unix epoch
def toMilliseconds($fmt):
  def toM:
    capture("(?<string>.*)[.](?<milliseconds>[0-9]+)Z")
    | .string += "Z"
    | .milliseconds |= tonumber;
  (toM // {string: ., milliseconds: 0})
  | (.string | strptime($fmt) | mktime) * 1000 + .milliseconds ;

{
    "horodate" : "2023-03-03T10:10:10.425Z"
}
 | .horodate
 | toMilliseconds("%Y-%m-%dT%H:%M:%SZ")

输出:
1677838210425

相关问题