如何使用 AWK 将时间戳转换为 UTC 时间

How to convert Timestamp in UTC time using AWK

我尝试使用 awk 处理邮件日志文件,但我在将时间戳转换为 UTC 格式时遇到问题。

输入文件如下所示:

# cat /tmp/TimeStamps1.tmp

2016-08-10T00:23:45.984558+02:00
2016-09-30T10:23:45.984558+02:00
2016-10-31T20:45:27.984558+01:00

预期输出应该是:

cat /tmp/Target

2016-08-09 22:23:45
2016-09-30 08:23:45
2016-10-31 19:45:27

由于日期和时间之间的 "T" 似乎是个问题,我也尝试将其删除:

# cat /tmp/TimeStamps2.tmp

2016-08-10 00:23:45.984558+02:00
2016-09-30 10:23:45.984558+02:00
2016-10-31 20:45:27.984558+01:00

首先尝试使用 system()

awk ' {print " - "system("date -u +%Y-%m-%d -d" [=13=]) } ' /tmp/TimeStamps2.tmp
date: extra operand `00:23:45.984558+02:00'
Try `date --help' for more information.
2016-08-10 - 1
date: extra operand `10:23:45.984558+02:00'
Try `date --help' for more information.
2016-09-30 - 1
date: extra operand `20:45:27.984558+01:00'
Try `date --help' for more information.
2016-10-31 - 1

第二次尝试使用 strftime()

/tmp$ awk -F',' ' {print " - "strftime( "%Y-%m-%d %H:%M:%S", )} ' /tmp/TimeStamps2.tmp
2016-08-10 00:23:45.984558+02:00 - 1970-01-01 01:33:36
2016-09-30 10:23:45.984558+02:00 - 1970-01-01 01:33:36
2016-10-31 20:45:27.984558+01:00 - 1970-01-01 01:33:36

这是第一个答案,感谢 Ed Morton!

awk ' { A=" ";system("date -u +%Y-%m-%d\" \"%T -d \""A"\""  ); } ' TimeStamps2.tmp
2016-08-09 22:23:45
2016-09-30 08:23:45
2016-10-31 19:45:27

现在听起来这就是您真正想要做的事情:

$ cat file
2016-08-10T00:23:45.984558+02:00 here is the first line
2016-09-30T10:23:45.984558+02:00 and here's the second
2016-10-31T20:45:27.984558+01:00 oh look, a third!

$ awk '{
    ts=; sub(/T/," ",ts); sub(/[^ ]+ /,"")
    cmd="date -u +\"%Y-%m-%d %T\" -d \"" ts "\""
    if ((cmd | getline line) > 0) {
        print line, [=10=]
    }
    close(cmd)
}' file
2016-08-09 22:23:45 here is the first line
2016-09-30 08:23:45 and here's the second
2016-10-31 19:45:27 oh look, a third!