How can I convert seconds to hours, minutes and seconds?
show_time() {
?????
}
show_time 36 # 00:00:36
show_time 1036 # 00:17:26
show_time 91925 # 25:32:0
I use the following function myself:
function show_time () {
num=$1
min=0
hour=0
day=0
if((num>59));then
((sec=num%60))
((num=num/60))
if((num>59));then
((min=num%60))
((num=num/60))
if((num>23));then
((hour=num%24))
((day=num/24))
else
((hour=num))
fi
else
((min=num))
fi
else
((sec=num))
fi
echo "$day"d "$hour"h "$min"m "$sec"s
}
Note it counts days as well. Also, it shows a different result for your last number.
All above is for bash, disregarding there "#!/bin/sh" without any bashism will be:
convertsecs() {
h=`expr $1 / 3600`
m=`expr $1 % 3600 / 60`
s=`expr $1 % 60`
printf "%02d:%02d:%02d\n" $h $m $s
}
#!/bin/sh
convertsecs() {
((h=${1}/3600))
((m=(${1}%3600)/60))
((s=${1}%60))
printf "%02d:%02d:%02d\n" $h $m $s
}
TIME1="36"
TIME2="1036"
TIME3="91925"
echo $(convertsecs $TIME1)
echo $(convertsecs $TIME2)
echo $(convertsecs $TIME3)
For float seconds:
convertsecs() {
h=$(bc <<< "${1}/3600")
m=$(bc <<< "(${1}%3600)/60")
s=$(bc <<< "${1}%60")
printf "%02d:%02d:%05.2f\n" $h $m $s
}
on MacOSX 10.13 Slight edit from @eMPee584 's code to get it all in one GO (put the function in some .bashrc like file and source it, use it as myuptime. For non-Mac OS, replace the T formula by one that gives the seconds since last boot.
myuptime ()
{
local T=$(($(date +%s)-$(sysctl -n kern.boottime | awk '{print $4}' | sed 's/,//g')));
local D=$((T/60/60/24));
local H=$((T/60/60%24));
local M=$((T/60%60));
local S=$((T%60));
printf '%s' "UpTime: ";
[[ $D > 0 ]] && printf '%d days ' $D;
[[ $H > 0 ]] && printf '%d hours ' $H;
[[ $M > 0 ]] && printf '%d minutes ' $M;
[[ $D > 0 || $H > 0 || $M > 0 ]] && printf '%d seconds\n' $S
}
In one line :
show_time () {
if [ $1 -lt 86400 ]; then
date -d@${1} -u '+%Hh:%Mmn:%Ss';
else
echo "$(($1/86400)) days $(date -d@$(($1%86400)) -u '+%Hh:%Mmn:%Ss')" ;
fi
}
Add days if exist.
The simplest way I know of:
secs=100000
printf '%dh:%dm:%ds\n' $(($secs/3600)) $(($secs%3600/60)) $(($secs%60))
Note - if you want days then just add other unit and divide by 86400.