我使用日期+“%T”打印开始和结束时间,结果如下:

10:33:56
10:36:10

我如何计算并打印这两者之间的差值呢?

我想要的是:

2m 14s

当前回答

或者把它包起来一点

alias timerstart='starttime=$(date +"%s")'
alias timerstop='echo seconds=$(($(date +"%s")-$starttime))'

这样就行了。

timerstart; sleep 2; timerstop
seconds=2

其他回答

我想提出另一种避免召回日期命令的方法。如果你已经收集了%T日期格式的时间戳,这可能会有帮助:

ts_get_sec()
{
  read -r h m s <<< $(echo $1 | tr ':' ' ' )
  echo $(((h*60*60)+(m*60)+s))
}

start_ts=10:33:56
stop_ts=10:36:10

START=$(ts_get_sec $start_ts)
STOP=$(ts_get_sec $stop_ts)
DIFF=$((STOP-START))

echo "$((DIFF/60))m $((DIFF%60))s"

我们甚至可以用同样的方法处理毫秒。

ts_get_msec()
{
  read -r h m s ms <<< $(echo $1 | tr '.:' ' ' )
  echo $(((h*60*60*1000)+(m*60*1000)+(s*1000)+ms))
}

start_ts=10:33:56.104
stop_ts=10:36:10.102

START=$(ts_get_msec $start_ts)
STOP=$(ts_get_msec $stop_ts)
DIFF=$((STOP-START))

min=$((DIFF/(60*1000)))
sec=$(((DIFF%(60*1000))/1000))
ms=$(((DIFF%(60*1000))%1000))

echo "${min}:${sec}.$ms"

截至目前(GNU coreutils) 7.4,你现在可以使用-d来做算术:

$ date -d -30days
Sat Jun 28 13:36:35 UTC 2014

$ date -d tomorrow
Tue Jul 29 13:40:55 UTC 2014

你可以使用的单位是天、年、月、小时、分钟和秒:

$ date -d tomorrow+2days-10minutes
Thu Jul 31 13:33:02 UTC 2014

如果你已经计算出了时间差值,并且它们小于1天,这里有一个非常边缘的BC用例,可以将输出格式化为

HH MM SS.xxxx

24小时格式,请记住小数点右边的数字是以60为基数打印的

Jot -w 'obase = 60;%。3f' - 1.3219567 300 73.6543211 | BC

       01.19 19
    01 14.58 33
    02 28.37 51
    03 42.17 06  # 3 mins 42 secs 
    04 55.56 20  
          ...
          ...
 19 38 10.54 32  # 19 hrs 38 mins 10 secs 
                 #
                 # (or 7:38pm, if it's representing absolute time)

但这绝对是一个快速得到大致数字的方法

这是我的bash实现(bit从其他SO;-)

function countTimeDiff() {
    timeA=$1 # 09:59:35
    timeB=$2 # 17:32:55

    # feeding variables by using read and splitting with IFS
    IFS=: read ah am as <<< "$timeA"
    IFS=: read bh bm bs <<< "$timeB"

    # Convert hours to minutes.
    # The 10# is there to avoid errors with leading zeros
    # by telling bash that we use base 10
    secondsA=$((10#$ah*60*60 + 10#$am*60 + 10#$as))
    secondsB=$((10#$bh*60*60 + 10#$bm*60 + 10#$bs))
    DIFF_SEC=$((secondsB - secondsA))
    echo "The difference is $DIFF_SEC seconds.";

    SEC=$(($DIFF_SEC%60))
    MIN=$((($DIFF_SEC-$SEC)%3600/60))
    HRS=$((($DIFF_SEC-$MIN*60)/3600))
    TIME_DIFF="$HRS:$MIN:$SEC";
    echo $TIME_DIFF;
}

$ countTimeDiff 2:15:55 2:55:16
The difference is 2361 seconds.
0:39:21

未测试,可能有bug。

% start=$(date +%s)
% echo "Diff: $(date -d @$(($(date +%s)-$start)) +"%M minutes %S seconds")"
Diff: 00 minutes 11 seconds