2

我有一个格式为 2012-12-20T01:16:02.05 的日期字符串,我想转换为格式 2011-12-20-01.16.02.050000

目前我这样做如下

format = "%F-%H.%M.%S.%N"
split(stringinput,input,"T"); 
split(input[1],date,"-")
split(input[2],time,":")

 return strftime(format,mktime(date[1] " " date[2] " " date[3] " " time[1] " " time[2] " " time[3] " " time[4]));

但我正在丢失微秒信息或毫秒信息。我怎么能得到那个。它正在返回 2011-12-20-01.16.02.%N

还有任何使字符串解析更通用的建议。目前它只支持一种格式。

谢谢。

4

3 回答 3

2

您将需要单独处理毫秒数据。此外,用于gensub()格式化您的字符串信息。像这样运行:

awk -f script.awk

内容script.awk

BEGIN {

    string = "2012-12-20T01:16:02.05"

    groups = "^(....)-(..)-(..).(..):(..):(..).*"
    format = "\\1 \\2 \\3 \\4 \\5 \\6"

    datespec = gensub(groups, format, "", string)
    timestamp = mktime(datespec)


    newstring = strftime("%F-%H.%M.%S", timestamp)

    sub(/.*\./,"",string)

    printf "%s.%s0000\n", newstring, string
}

结果:

2012-12-20-01.16.02.050000

编辑:

BEGIN {

    string = "2011-01-10T14:45:13.815-05:00"

    groups = "^(....)-(..)-(..).(..):(..):(..).*"
    format = "\\1 \\2 \\3 \\4 \\5 \\6"

    datespec = gensub(groups, format, "", string)
    timestamp = mktime(datespec)


    sub(/.*\./,"",string)

    offset = substr(string,4)

    split(offset,array,":")

    seconds = (array[1] * 60 * 60) + (array[2] * 60)

    newstring = strftime("%F-%H.%M.%S", timestamp - seconds, 1)

    printf "%s.%s00\n", newstring, substr(string,0,3)
}

结果:

2011-01-10-09.45.13.81500
于 2013-02-21T06:18:40.417 回答
1

Why are you using mktime()? The change you describe is just a text change:

$ echo "2012-12-20T01:16:02.05" | awk '{sub(/T/,"-"); gsub(/:/,"."); print $0 "0000"}'
2012-12-20-01.16.02.050000

I'm assuming it was just a typo when you changed 2012 to 2011 in your output.

于 2013-02-21T12:19:44.520 回答
0

因为我希望我的 GNU 日期精度与 awk 匹配,所以我必须按以下方式进行:

x='2019-05-30 14:09:20.074'
echo $x | awk '{split($1,a,"-");;split($2,b,".");split(b[1],c,":");s=a[1]" "a[2]" "a[3]" "c[1]" "c[2]" "c[3];tt=mktime(s);print tt b[2] "000000"}'
1559196560074000000

date --date=$x +'%s%N'
1559196560074000000

现在,我能够使这两者达成一致,我现在能够在 awk 中进行比较逻辑。

于 2019-05-30T21:39:51.520 回答