我有一个格式为 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
还有任何使字符串解析更通用的建议。目前仅支持一种格式。
谢谢。
最佳答案
您需要单独处理毫秒数据。另外,使用 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
关于date - 在awk中使用mktime时如何保留毫秒信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14995317/