如何在 AWK 中给定时间戳添加秒或分钟

如何在 AWK 中给定时间戳添加秒或分钟

鉴于我有以下 awk 脚本:

#!/usr/bin/awk -f

BEGIN {
  startTimestamp = ARGV[1];
  endTimestamp = ARGV[2];

  print startTimestamp
  print endTimestamp
  print startTimestamp + 60 seconds
  print endTimestamp + 10 minutes
}

我想为给定参数添加秒或分钟:startTimestampendTimestamp

例如,我可以调用此脚本,./print-timestamps.awk 2018-10-14T13:26:00.000 2018-10-14T13:27:50.000 并且我希望打印:

2018-10-14T13:26:00.000
2018-10-14T13:27:50.000
2018-10-14T13:27:00.000
2018-10-14T13:37:50.000

我怎样才能做到这一点?

答案1

GNUawkmktimestrftime

$ gawk '{gsub(/[-T:]/," "); print strftime("%Y-%m-%dT%H:%M:%S\n", mktime($0)+60)}'

$ gawk '
    function timeadd(t, s){
        gsub(/[-T:]/," ", t); return strftime("%Y-%m-%dT%H:%M:%S", mktime(t)+s)
    }
    BEGIN{
        print ARGV[1]
        print ARGV[2]
        print timeadd(ARGV[1], 60)
        print timeadd(ARGV[2], 60 * 10)
    }
' 2018-10-14T13:26:00.000 2018-10-14T13:27:50.000
2018-10-14T13:26:00.000
2018-10-14T13:27:50.000
2018-10-14T13:27:00
2018-10-14T13:37:50

它的一个版本timeadd也处理毫秒:

$ cat timeadd.awk
function timeadd(t, s){
    gsub(/[-T:]/," ", t)
    t = mktime(t) + s + substr(t, index(t, "."))
    s = substr(sprintf("%.3f", t - int(t)), 2)
    return strftime("%Y-%m-%dT%H:%M:%S" s, t)
}
{ print timeadd($1, $2); }

$ gawk -f /tmp/timeadd.awk
2018-10-19T13:26:58.815 4.237
2018-10-19T13:27:03.052
2018-10-19T13:26:58.122 -3.822
2018-10-19T13:26:54.300

答案2

GNUdate可用吗?尝试

awk '
BEGIN {
  startTimestamp = ARGV[1];
  endTimestamp = ARGV[2];

  print startTimestamp
  sub (/T/, " ", startTimestamp)
  print endTimestamp
  sub (/T/, " ", endTimestamp)
  system ("date +\"%FT%T\" -d\"" startTimestamp " 60 seconds\"")
  system ("date +\"%FT%T\" -d\"" endTimestamp " 60 minutes\"")
} ' 2018-10-14T13:26:00.000 2018-10-14T13:27:50.000
2018-10-14T13:26:00.000
2018-10-14T13:27:50.000
2018-10-14T13:27:00
2018-10-14T14:27:50

相关内容