7

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.

14

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

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.

  • great solution. – Tim Kennedy Feb 12 '11 at 16:55
  • Exactly what I would have done. Looks like it depends on GNU date though; see the question Steven D linked to. – Jander Feb 12 '11 at 20:20
2

If you don't mind an external helper utility, have a look at my dateutils. Above task translates to:

ddiff -i '%b %d %H:%M:%S' 'Feb 12 10:02:10' 'Feb 12 10:53:15'
=> 
  3065s

where -i is used to describe the input date format.

1

Another solution without bc

1. Convert the dates to Unix time (also known as POSIX time or UNIX Epoch time)

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

date2=date -d "Feb 12 10:53:15" +%s

user@linux:~$ echo -e "$date1\n$date2"
1518447730
1518450795
user@linux:~$ 

2. Calculate the difference between 2 dates

let datediff="date2-date1"

3. You'll the answer in seconds

user@linux:~$ echo $datediff
3065
user@linux:~$

4. Convert it to hours, minutes, and seconds format

user@linux:~$ printf '%02dh:%02dm:%02ds\n' $(($datediff/3600)) $(($datediff%3600/60)) $(($datediff%60))
00h:51m:05s
user@linux:~$ 

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.