Calculating durations in Unix
What's the duration of a process that starts at 10:00:05 and stops at 10:01:24?
How much time has elapsed between 2013-08-06 23:17:34 and 2013-08-07 06:20:03?
We can figure out the answer to these questions and more by converting the start and end date/time strings into Unix timestamps using date
(seconds since the epoch). Then, subtracting the start timestamp from the end (using expr
) gives us the duration in seconds.
Here's a simple shell script that demonstrates the technique:
timestamp(){
date -j -f "%F %T" $* +%s
}
starttime=$(timestamp $1)
endtime=$(timestamp $2)
duration=$(expr $endtime - $starttime)
echo "Duration (seconds): $duration"
Feeding our examples to the script looks like this:
./duration.sh 2013-08-0623:17:34 2013-08-0706:20:03
Duration (seconds): 25349
./duration.sh 2013-08-0610:00:05 2013-08-0610:01:24
Duration (seconds): 79
Sidebar: Notice we squash the date and time together, 2013-08-0610:10:24
, when calling the script. This is because bash separates command line arguments by spaces. Our timestamp
function doesn't care, though, because date
strips whitespaces from the mask and the input before transformation.