正确格式的两个时间戳的差异

时间:2018-01-16 13:33:13

标签: python shell unix

我有2个时间戳,格式为YYYYMMDDHHMMSS。

d1=20180110141907
d2=20180110141907

我想要一个shell脚本,找出上述两个日期之间的差异,并将输出设为“4days 22hrs 56min 04sec”。

2 个答案:

答案 0 :(得分:0)

如果你的时间stam是unix时间

[[1, 2], [3, 4], [5, 6]]

答案 1 :(得分:0)

这并不困难,但确实需要几个步骤:解析传入的时间格式,找出差异的秒数,并计算差异的不同时间单位。

鉴于

d1=20180110141907
d2=20180111162211

GNU awk

gawk -v start="$d1" -v stop="$d2" '
    function str2time(time,    re, arr, t) {
        re = "([[:digit:]]{4})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})([[:digit:]]{2})"
        t = -1
        if (match(time, re, arr))
            t = mktime(arr[1] " " arr[2] " " arr[3] " " arr[4] " " arr[5] " " arr[6])
        return t
    }
    BEGIN {
        t1 = str2time(start)
        t2 = str2time(stop)
        diff = t2 - t1
        if (diff < 0) diff = -diff       #awk does not have abs()
        days  = int(diff / 86400); diff %= 86400
        hours = int(diff / 3600);  diff %= 3600
        mins  = int(diff / 60);    diff %= 60
        printf("%d days %d hours %d mins %d secs\n", days, hours, mins, diff)
    }
'
1 days 2 hours 3 mins 4 secs

的Perl

perl -MTime::Piece -sE '
    $t1 = Time::Piece->strptime($start, "%Y%m%d%H%M%S");
    $t2 = Time::Piece->strptime($stop,  "%Y%m%d%H%M%S");
    $diff = abs($t2 - $t1);
    $days  = int($diff / 86400); $diff %= 86400;
    $hours = int($diff / 3600);  $diff %= 3600;
    $mins  = int($diff / 60);    $diff %= 60;
    printf "%d days %d hours %d mins %d secs\n", $days, $hours, $mins, $diff;
' -- -start="$d1" -stop="$d2"
1 days 2 hours 3 mins 4 secs