0

grep timestamp in a file as given below. Now I need to calculate time difference

file data:

18:29:10
04:56:50

I tried following command its output is in minus:

awk -F":" 'FNR==1{split($0,a,":");sec1=a[1]*3600+a[2]*60+a[3]} FNR==2{split($0,b,":");sec2=b[1]*3600+b[2]*60+b[3];val=sec2-sec1;ho=int(val/3600);val=val%3600;mi=sprintf("%02d",(val/60));val=val%60;;print ho":"mi":"val}' file.txt

Output is: -13:-32:-10

I want output like: 10:27:40

2
  • 1
    Downvoted for confusing the hell out of my debugging by including TWO wrong outputs. Please fix. – Wildcard Jan 4 '18 at 10:09
  • 3
    how can you tell which day these times are for? e.g what information is available to determine where 04:56:50 is the morning of the same day as 18:29:10, or the next morning? or some morning next or last week? i.e. don't throw away the date portion of the timestamp when it's still needed. – cas Jan 5 '18 at 2:13
2

Assuming you meant 10:27:40

awk -F: '
  {t[NR] = $3 + 60 * ($2 + 60 * $1)}
  END{
    d = t[2] - t[1]
    if (d < 0) d += 86400
    h = d / 3600
    d %= 3600
    m = d / 60
    s = d % 60
    printf "%02d:%02d:%02d\n", h, m, s
  }'
3

With GNU date:

string1="18:29:10"
string2="04:56:50"
StartDate=$(date -u -d "$string1" +"%s")
FinalDate=$(date -u -d "$string2" +"%s")
date -u -d "0 $FinalDate sec - $StartDate sec" +"%H:%M:%S"

Output:

10:27:40

Credits: https://stackoverflow.com/a/27442175/3776858

0

Just for fun, using dc:

$ cat file.txt
18:29:10
04:56:50
$ tr : \ <file.txt | dc -f - -e 'r60*+r60d**+r-r60*-r60d**-60dod24**+p'
 10 27 40
$ 

This was my first dc script. Fun learning experience.


Another approach using dc:

$ cat file.txt 
18:29:10
04:56:50
$ cat time_subtract.dc 
[r60*+r60d**+]sb60d24**sd[ld+d0>n]snlbxsflbx_1*lf+60od0>np
$ tr : \ <file.txt | dc -f - -f time_subtract.dc 
 10 27 40
$ 

Finally, nicely wrapped up in a shell script so it can be run as ./script.sh file.txt or some pipeline | ./script.sh, we have:

#!/bin/sh
cat "$@" |
tr : ' ' |
  dc -e '
[60+Lm1-Sm]SS
[60+Lh1-Sh]SM
[24+]SH
?SsSmSh
?SsSmSh
LsLs- d0>S Ss
LmLm- d0>M Sm
LhLh- d0>H Sh
[
]Ls[:]Lm[:]Lh
nnnnnn
'

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.