Shell – How to get elapsed time from two “text based” dates

dateshell-script

I would like to know if there is a way to calculate the difference between two times in bash. I have two fields that are extracted from a log file:

Start time: Feb 12 10:02:10
End time: Feb 12 10:53:15

What I need is a manual way to get the elapsed time between these 2 dates. Since the time values are "text based", and not from a date generating command, I don't know if there's a way to do it. The times are 24 hour based, so hopefully that'll make times spanning midnight easier to handle. Any suggestions will be greatly appreciated.
Peter V.

Best Answer

You could use some evil trickery:

date -d "Feb 12 10:02:10" +%s

will return the number of seconds since the epoch for that date. Combining this with the same command (for the other date) and running through bc:

echo "$(date -d 'Feb 12 10:53:15' +%s) - $(date -d 'Feb 12 10:02:10' +%s)" | bc

or the shell's arithmetic expansion:

echo "$(( $(date -d 'Feb 12 10:53:15' +%s) - $(date -d 'Feb 12 10:02:10' +%s) ))"

will give you

3065

the number of seconds between the times. You could probably parse this out with awk somehow if you needed to run it more than once.

Related Question