0

Is there a way that we can get the time difference in hh:mm:ss format in a shell script?

E.g.,

"StartDateTime": "2020-10-06T20:36:15.706000+05:30",
"EndDateTime": "2020-10-06T21:15:44.505000+05:30",

I was trying to calculate the duration as (EndDateTime-StartDateTime) but doesn't seem to yield the desrired result. Can someone guide me ?

techPM
  • 89
  • 1
  • 7
  • 2
    Do you seen this response : https://stackoverflow.com/questions/8116503/how-to-compare-two-datetime-strings-and-return-difference-in-hours-bash-shell – YLR Oct 08 '20 at 07:07
  • 1
    `Can someone guide me ?` 1. Convert dates to seconds since epoch. 2. Substract seconds since epoch. 3. Convert seconds to hh:mm:ss using simple maths – KamilCuk Oct 08 '20 at 07:17
  • @YLR, the suggestion made by you might work for the data that doesn't have timezone specified. I think I may have to use a custom script to truncate the datetime format to a different format and convert to seconds – techPM Oct 08 '20 at 11:27

1 Answers1

0

An awk solution with the example text in the file datestamp

  awk -F [\"-.T] '
               /^\"StartDateTime/ { yr=$5;
                                   mn=$6;
                                   dd=$7;
                                   split($8,tim,":") 
                                  } 
               /^\"EndDateTime/ {   yr1=$5;
                                    mn1=$6;
                                    dd1=$7;
                                    split($8,tim1,":") 
                                   } 
                END {               dat1=yr1" "mn1" "dd1" "tim1[1]" "tim1[2]" 
                                    "tim1[3];
                                    dat2=yr" "mn" "dd" "tim[1]" "tim[2]" 
                                    "tim[3];
                                    timdiff=mktime(dat1)-mktime(dat2);
                                    print timdiff/60 
                     }' datestamp

We set up field separators in order to parse the lines in order to extract years, months, days, hours, minutes and seconds. We set up variables for each of these referencing start and end dates/times. We then use awks mktime function to get the epoch format of the start and end dates, get the difference in epoch format and then get an approximate difference in seconds, dividing by 60 to get the difference in minutes.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18