user3834663
user3834663

Reputation: 543

Calculate time difference using awk

I have the following input.txt file. I need to calculate the time difference of $2 and $3 and print difference in hours.

P1,       2016-05-30 00:11:20,    2016-05-30 04:36:40
P2,       2016-05-30 00:07:20,    2016-05-30 04:32:31

I have the following code, but it looks like the hours is not showing accurate. Please help.

awk -F, '{gsub(/[-:]/," ",$2);gsub(/[-:]/," ",$3);
          d2=mktime($3);d1=mktime($2);
          print $1","(d2-d1)/3600,"hrs";}' input.txt

I am getting the output like this.

P1,4.42222 hrs
P2,4.41972 hrs

but it should be showing of a difference 4:25:20 hrs 4:25:11 hrs

Thanks in advance

Upvotes: 5

Views: 3998

Answers (2)

Ed Morton
Ed Morton

Reputation: 203169

$ cat tst.awk
BEGIN { FS=",[[:space:]]+"; OFS="," }
function dt2secs(dt) { return mktime(gensub(/[-:]/," ","g",dt)) }
function secs2hms(s) { return sprintf("%d:%02d:%02d hrs",s/(60*60),(s/60)%60,s%60) }
{ print $1, secs2hms(dt2secs($3)-dt2secs($2)) }

$ awk -f tst.awk file
P1,4:25:20 hrs
P2,4:25:11 hrs

Upvotes: 3

rici
rici

Reputation: 241671

If you want to print a number of seconds in HH:MM:SS syntax, you'll need to do the computation yourself. Using printf will prove useful if you want to print, for example, 4:02:30 instead of 4:2:30. For example,

secs = d2 - d1;
printf "%s, %d:%02d:%02d hrs.\n", $1, int(secs/3600), int(secs/60)%60, secs%60

Upvotes: 3

Related Questions