问题
Gnu AWK provides the built in function
strftime()
which can convert a timestamp like 1359210984
into Sat 26. Jan 15:36:24 CET 2013
.
I couldn't find a function that would do this:
seconds = timefromdate("Sat 26. Jan 15:36:24 CET 2013", "%a %d. %b %H:%M:%S CET %Y")
or
seconds = timefromdate("2013-01-26 15:36:24", "%Y-%m-%d %H:%M:%S")
Whereas seconds
then is 1359210984
.
So, the date string should be convertable by a format pattern.
I'd like to do this in gawk only.
Edit 1:
I'd like to convert the date only in gawk for further processing of the stream.
Edit 2:
I've clarified my question. It was a bit sloppy in the "would do this" code example.
回答1:
The function you're looking for is called mktime()
. You should use the gensub()
function to manipulate the datespec into the format that can be read by mktime()
.
To format the second example that you give, consider:
BEGIN {
t = "2013-01-26 15:36:24"
f = "\\1 \\2 \\3 \\4 \\5 \\6"
s = mktime(gensub(/(....)-(..)-(..) (..):(..):(..)/, f, "", t))
print s
}
Results on my machine:
1359178584
To format the first example that you give, consider:
BEGIN {
t = "Sat 26. Jan 15:36:24 CET 2013"
gsub(/\.|:/, FS, t)
split(t,a)
Y = a[8]
M = convert(a[3])
D = a[2]
h = a[4]
m = a[5]
s = a[6]
x = mktime(sprintf("%d %d %d %d %d %d", Y, M, D, h, m, s))
print x
}
function convert(month) {
return(((index("JanFebMarAprMayJunJulAugSepOctNovDec", month) - 1) / 3) + 1)
}
Results on my machine:
1359178584
For more information, please consult the manual, specifically time functions and string functions. HTH.
来源:https://stackoverflow.com/questions/14537954/gawk-inverse-of-strftime-convert-date-string-to-seconds-since-epoc-timestam