Sriram
Sriram

Reputation: 10558

Subtract one time from another - bash

I have a text file that contains date, and two time-strings separated by spaces (a lot of these) in the format as given below:

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

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

2011-03-05 0:0:1  

The text file is made up of a lot of lines of the above format.

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

Any help is most welcome,
Sriram

Upvotes: 3

Views: 4438

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

For time arithmetic, I find it's easier to use a language with built-in time functions. For example, in 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

Upvotes: 1

dogbane
dogbane

Reputation: 274532

Here is a simple awk script which does not use any time functions:

$ 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;
}

The input data:

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

Run it:

$ awk -f subtract.awk < file.txt

2011-03-05 0:0:1

Alternatively, you can use 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;
}

Upvotes: 3

Related Questions