Subtract once from another - bash

I have a text file containing a date and two temporary lines separated by spaces (many of them) in the format shown below:

2011-03-05 15:16:41 15:16:42  

My question is this:
Using awk, how can I separate time points, assign them to variables, and then subtract them? The answer to the line above would be something like this:

2011-03-05 0:0:1  

A text file consists of a large number of lines of the specified format.

I went through SO and see that there are a lot of arithmetic questions by date and time, but none of them seem to fit this particular requirement.

Any help is appreciated,
Sriram

+3
source share
2 answers

awk script, :

$ cat subtract.awk

{
hh1=substr($2,1,2);
mm1=substr($2,4,2);
ss1=substr($2,7,2);

hh2=substr($3,1,2);
mm2=substr($3,4,2);
ss2=substr($3,7,2);

time1=hh1*60*60 + mm1*60 + ss1;
time2=hh2*60*60 + mm2*60 + ss2;

diff=time2-time1;

printf "%s %d:%d:%d\n",$1,diff/(60*60),diff%(60*60)/60,diff%60;
}

:

$ cat file.txt
2011-03-05 15:16:41 15:16:42

:

$ awk -f subtract.awk < file.txt

2011-03-05 0:0:1

, mktime:

{
    date=$1
    gsub(/[-:]/," "); 
    diff=mktime ($1" "$2" "$3" "$7" "$8" "$9) - mktime ($1" "$2" "$3" "$4" "$5" "$6);  
    printf "%s %d:%d:%d\n",date,diff/(60*60),diff%(60*60)/60,diff%60;
}
+3

. , Tcl

set line "2011-03-05 15:16:41 15:16:42"
lassign [split $line] date time1 time2
set base [clock scan $date -format %Y-%m-%d]
set t1 [clock scan $time1 -format %T]
set t2 [clock scan $time2 -format %T]
set diff [expr {abs($t2 - $t1)}]
puts [clock format [clock add $base $diff seconds] -format "%Y-%m-%d %T"]
# ==> 2011-03-05 00:00:01
+1

All Articles