Convert time stamp to seconds in bash
As far as I know, bash variables do not have a certain type.
My problem is, I need to convert a time stamp (always in format: hh:mm:ss
) to a single integer representing seconds.
So I cut the hh
, mm
and ss
parts into separate strings and use expr
to calculate the seconds integer like:
TIME=expr $HH \* 3600 + $MM \* 60 + $SS
But when e.g. $HH=00
then expr won't work. Is it possible to convert strings like 00
or 01
to integers?
Try awk
. For example:
echo "00:20:40" | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }'
So, if you have:
time="00:20:40"
then:
seconds=$(echo $time | awk -F: '{ print ($1 * 3600) + ($2 * 60) + $3 }')
and echo $seconds
will print 1240
.
If you want to convert the current time into second, try this script
#!/bin/bash
let var=$(date +%H)*3600+$(date +%M)*60+$(date +%S)
echo $var
It will convert the current time into seconds (an integer).
If you wish to convert an arbitrary time string like HH:MM:SS
into second then it is better to use Radu Rădeanu's answer. I could give something in the way you were trying,
I am assuming you stored hour, min, and second in HH
, MM
and SS
, then use the following to store time in second into var
,
let var=HH*3600+MM*60+SS