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.


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


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

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'

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


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)

$ printf '%s\n' "$date1" "$date2"

2. Calculate the difference between the two dates

$ datediff="$((date2-date1))"

3. You'll get the answer expressed in seconds

$ echo "$datediff"

4. Convert it to hours, minutes and seconds format

$ printf '%02dh:%02dm:%02ds\n' $(($datediff/3600)) $(($datediff%3600/60)) $(($datediff%60))


$ TZ=UTC date '+%H:%M:%S' -d"@$datediff"

Be alert to the possibility that the result is ≥ 86400 (i.e., 24 hours) and adjust the format accordingly.

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.