Bash将字符串转换为时间戳

时间:2014-10-17 19:24:39

标签: bash sh

我有一个格式为20141225093000的字符串,表示Dec 25, 2014 09:30:00,我想将原始格式转换为unix时间戳格式,以便我可以对它进行时间操作。如何在bash中执行此操作?

我可以使用expr轻松解析值,但我希望能够识别YYYYmmddHHMMSS之类的格式,然后根据它进行转换。

4 个答案:

答案 0 :(得分:4)

使用GNU日期,您可以轻松地将YYYY-MM-DDTHH:MM:SS转换为纪元时间(自1-1-1970以来的秒数),如下所示:

date -d '2014-12-25T09:30:00' +%s

要在没有任何分隔符的情况下开始这样做:

in=20141225093000
rfc_form="${in:0:4}-${in:4:2}-${in:6:2}T${in:8:2}:${in:10:2}:${in:12:2}"
epoch_time=$(date -d "$rfc_form" +%s)

答案 1 :(得分:1)

您需要在调用date之前转换字符串:

#!/bin/bash

s="20141225093000"
s=$(perl -pe 's/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/$1-$2-$3 $4:$5:$6/g' <<< "$s")
date -d "$s" +%s

另一种方式:

perl -MDate::Parse -MPOSIX -le '$s="20141225093000"; $s =~ s/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/$1-$2-$3 $4:$5:$6/g ; print str2time($s);'
1419499800

答案 2 :(得分:1)

GNU awk:

gawk -v t=20141225093000 'BEGIN {gsub(/../, "& ", t); sub(/ /,"",t); print mktime(t)}'

如果GNU日期不可用,那么它可能不是GNU awk。 Perl可能具有最高的可用性。此代码段使用strptime,因此您根本不必解析时间字符串:

perl -MTime::Piece -E 'say Time::Piece->strptime(shift, "%Y%m%d%H%M%S")->epoch' 20141225093000

答案 3 :(得分:1)

这个Bash函数使用builtins进行转换:

# Convert UTC datetime string (YYYY-MM-DD hh:mm:ss) to Unix epoch seconds
function ymdhms_to_epoch
{
    local -r ymdhms=${1//[!0-9]}    # Remove non-digits

    if (( ${#ymdhms} != 14 )) ; then
        echo "error - '$ymdhms' is not a valid datetime" >&2
        return 1
    fi

    # Extract datetime components, possibly with leading zeros
    local -r year=${ymdhms:0:4}
    local -r month_z=${ymdhms:4:2}
    local -r day_z=${ymdhms:6:2}
    local -r hour_z=${ymdhms:8:2}
    local -r minute_z=${ymdhms:10:2}
    local -r second_z=${ymdhms:12:2}

    # Remove leading zeros from datetime components to prevent them
    # being treated as octal values
    local -r month=${month_z#0}
    local -r day=${day_z#0}
    local -r hour=${hour_z#0}
    local -r minute=${minute_z#0}
    local -r second=${second_z#0}

    # Calculate Julian Day Number (jdn)
    # (See <http://en.wikipedia.org/wiki/Julian_day>, Calculation)
    local -r -i a='(14-month)/12'
    local -r -i y=year+4800-a
    local -r -i m=month+12*a-3
    local -r -i jdn='day+(153*m+2)/5+365*y+(y/4)-(y/100)+(y/400)-32045'

    # Calculate days since the Unix epoch (1 Jan. 1970)
    local -r -i epoch_days=jdn-2440588

    local -r -i epoch_seconds='((epoch_days*24+hour)*60+minute)*60+second'

    echo $epoch_seconds

    return 0
}

使用示例:

$ ymdhms_to_epoch '1970-01-01 00:00:00'
0
$ ymdhms_to_epoch '2014-10-18 00:10:06'
1413591006
$ ymdhms_to_epoch '2014-12-25 09:30:00'
1419499800