Convert seconds to hours, minutes, seconds
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:05
Use date, converted to UTC:
$ date -d@36 -u +%H:%M:%S
00:00:36
$ date -d@1036 -u +%H:%M:%S
00:17:16
$ date -d@12345 -u +%H:%M:%S
03:25:45
The limitation is the hours will loop at 23, but that doesn't matter for most use cases where you want a one-liner.
On macOS, run brew install coreutils
and replace date
with gdate
#!/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
}