How to subtract two times in shell
13,284
Solution 1
I would take a step further (inspired by this post):
# => 18:23:24 --> 66204
grep usb /var/log/kern.log|tail -2|awk '{print $3}'|awk -F: '{print ($1 * 3600) + ($2 * 60) + $3 }'
So, after I had:
66204
66020
You could then do:
echo $((66204-66020)) # => 184
Solution 2
A more general solution because it works with times from different dates, too:
echo "18:23:24
18:20:20" |
(read later_time; read former_time;
former_seconds=$(date --date="$former_time" +%s);
later_seconds=$(date --date="$later_time" +%s);
echo $((later_seconds-former_seconds)) )
184
Comments
-
Rakesh R Nair almost 2 years
I nee to subtract two lines which is in the format of time in shell. The time format is hh:mm:ss I used the code below to get the time.
cat /var/log/kern.log |grep usb |tail -2| awk '{print $3}'
The output of the above code is
18:23:24 18:20:20
How can I find the difference in seconds?
-
Admin over 9 yearsWhy are you piping awk into awk ?
-
Admin over 9 years@Costas, there are only ever going to be two at the end of that pipe so it works fine, also the $2 was a typo and has been fixed :)
-
Costas over 9 yearsSorry I miss idea to remail all pipes
-
Soinou over 9 yearsI'm separating concerns: the first
awk
gives me the hh:mm:ss format. The secondawk
transforms the hhh:mm:ss into integers. For me, it cuts down on cognitive load. -
Soinou over 9 years@DarkHeart: what would you recommend?