Search code examples
bashdatetimelsdate-arithmeticstat

how to calculate total elapsed time


how to calculate elapsed time based on

start time=

[user001a@dev51 logs]# grep 'Recovery Manager' 
refresh_03Jun2019_0250.log|head -1|awk -F'on ' '{print $NF}';
Jun 3 02:50:02 2019
[user001a@dev51 logs]#

end time=

[user001a@dev51 logs]# ls -l refresh_03Jun2019_0250.log
-rw-r--r--. 1 user001a grp001a 170050 Jun  3 05:06 
refresh_03Jun2019_0250.log
[user001a@dev51 logs]#

Note - stat is missing birth time so stat might not be a good option time calculate file create and modify time:

[user001a@dev51 logs]# stat refresh_03Jun2019_0250.log
  File: `refresh_03Jun2019_0250.log'
  Size: 170050          Blocks: 344        IO Block: 4096   regular file
Device: 811h/2065d      Inode: 1474545     Links: 1
Access: (0644/-rw-r--r--)  Uid: (  219/  user001a)   Gid: (  219/grp001a)
Access: 2019-06-03 05:06:40.830829026 -0400
Modify: 2019-06-03 05:06:40.827828883 -0400
Change: 2019-06-03 05:06:40.827828883 -0400
[user001a@dev51 logs]#

Sample1 output:

StartTime=June 3, 2019 at 2:50:02 am
EndTime=June 3, 2019 at 5:06:40 am
ElapsedTime=2 hours, 16 minutes and 38 seconds

Sample2 output:

ElapsedTime=2 hours, 16 minutes and 38 seconds

Solution

  • Limitation of this solution: Max 23 hours. For more, days need to be added.

    StartTime="June 3, 2019 at 2:50:02 am"
    EndTime="June 3, 2019 at 5:06:40 am"
    StartTimeInEpoch=`echo $StartTime | sed 's/at //g' | date -f- +"%s"`
    EndTimeInEpoch=`echo $EndTime | sed 's/at //g' | date -f- +"%s"`
    echo $EndTimeInEpoch-$StartTimeInEpoch | bc | sed 's/^/@/g' | date -u -f- "+%_H hours %_M minutes %_S seconds"
    

    Output:

    2 hours 16 minutes 38 seconds
    

    Assuming you've got your dates in variables StartTime and EndTime. It's necessary to remove at from them, sed do this. Then both dates are converted to epoch time +"%s" do the trick. -f- tells date to take date from stdin (pipe). Then we can subtract the dates, add @ to the beginning and format with date. -u mean UTC time - no time shift.