6

The following two variables contain the start time and the end time , need to get the difference between these two time in seconds

start_time=06:07:25
end_time=07:02:08

Desired Output

diff_time= 3283 Seconds

I use AIX 6.1 machine with ksh88.

  • Is it possible to get your timestamps in a different format? This becomes much easier if you, e.g., use date +%s to get your start and end times... Further, assuming localtime, what you want to do isn't actually possible in general with the format you have (consider what happens if you cross a daylight saving time boundary). – derobert Oct 23 '13 at 19:22
  • Does AIX date have the -d switch? I think it doesn't but I'm not sure. – terdon Oct 23 '13 at 19:30
  • @terdon No, only GNU and BusyBox do. – Gilles 'SO- stop being evil' Oct 23 '13 at 23:08
7

using bash:

t2s()
{
  local T=$1;shift
  echo $((10#${T:0:2} * 3600 + 10#${T:3:2} * 60 + 10#${T:6:2})) 
}

start_time=06:07:25
end_time=07:02:08

diff_time=$(( $(t2s $end_time) - $(t2s $start_time) ))
6

If you're sure that end_time is always greater than start_time, you can use Perl like so:

export start_time=06:07:25
export end_time=07:02:08
perl -e '
    ($h1,$m1,$s1) = split /:/,$ENV{start_time};
    ($h2,$m2,$s2) = split /:/,$ENV{end_time};
    $delta_h = $h2 - $h1;
    $delta_m = $m2 - $m1;
    if( $delta_m < 0 ) { $delta_m = $delta_h-- * 60 + $m2 - $m1; }
    $delta_s = $s2 - $s1;
    if( $delta_s < 0 ) { $delta_s = $delta_m-- * 60 + $s2 - $s1; }
    print "diff_time=", $delta_h * 3600 + $delta_m * 60 + $delta_s, " seconds\n"
'

Note that you can do this purely in {k,}sh with parameter expansion and shell arithmetic. I'm just using Perl for convenience.

Here it is in POSIX shell script:

start_time=06:07:25
end_time=07:02:08
h1=${start_time%%:*}
start_time=${start_time#*:}
m1=${start_time%%:*}
s1=${start_time#*:}
h2=${end_time%%:*}
end=${end#*:}
m2=${end_time%%:*}
s2=${end_time#*:}
delta_h=$(( h2 - h1 ))
delta_m=$(( m2 - m1 ))
if [ $delta_h -lt 0 ];then
    delta_m=$(( delta_h * 60 + m2 -m1 ))
    delta_h=$(( delta_h - 1 ))
fi
delta_s=$(( s2 - s1 ))
if [ $delta_s -lt 0 ];then
    delta_s=$(( delta_m * 60 + s2 - s1 ))
    delta_m=$(( delta_m - 1 ))
fi
delta_all=$(( delta_h * 3600 + delta_m * 60 + delta_s ))
printf "diff_time = %d seconds\n" $delta_all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.