GAWK:strftime()的逆函数-使用格式模式将日期字符串转换为自epoc时间戳以来的秒数 [英] GAWK: Inverse of strftime() - Convert date string to seconds since epoc timestamp using format pattern

查看:128
本文介绍了GAWK:strftime()的逆函数-使用格式模式将日期字符串转换为自epoc时间戳以来的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Gnu AWK提供了内置功能

Gnu AWK provides the built in function

strftime()

可以将类似1359210984的时间戳转换为Sat 26. Jan 15:36:24 CET 2013. 我找不到可以执行此操作的函数:

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")

seconds = timefromdate("2013-01-26 15:36:24", "%Y-%m-%d %H:%M:%S")

seconds则为1359210984.

因此,日期字符串应该可以通过格式模式进行转换.

So, the date string should be convertable by a format pattern.

我只想在gawk中这样做.

I'd like to do this in gawk only.

我只想将日期转换为gawk以便进一步处理流.

I'd like to convert the date only in gawk for further processing of the stream.

我已经澄清了我的问题.在将要这样做"中,这有点草率.代码示例.

I've clarified my question. It was a bit sloppy in the "would do this" code example.

推荐答案

您要查找的函数称为mktime().您应该使用gensub()函数将datespec操纵为mktime()可以读取的格式.

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
}

我的机器上的结果:

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)
}

我的机器上的结果:

1359178584


有关更多信息,请查阅手册,特别是时间函数


For more information, please consult the manual, specifically time functions and string functions. HTH.

这篇关于GAWK:strftime()的逆函数-使用格式模式将日期字符串转换为自epoc时间戳以来的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆