Calculate Time difference between two lines

7,123

Solution 1

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
  }'

Solution 2

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

Share:
7,123
Vivek Nigam
Author by

Vivek Nigam

Updated on September 18, 2022

Comments

  • Vivek Nigam
    Vivek Nigam over 1 year

    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

    • Wildcard
      Wildcard over 6 years
      Downvoted for confusing the hell out of my debugging by including TWO wrong outputs. Please fix.
    • Alessio
      Alessio over 6 years
      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.