Convert seconds to hours, minutes, seconds
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
Simple one-liner
$ secs=236521
$ printf '%dh:%dm:%ds\n' $((secs/3600)) $((secs%3600/60)) $((secs%60))
65h:42m:1s
With leading zeroes
$ secs=236521
$ printf '%02dh:%02dm:%02ds\n' $((secs/3600)) $((secs%3600/60)) $((secs%60))
65h:42m:01s
With days
$ secs=236521
$ printf '%dd:%dh:%dm:%ds\n' $((secs/86400)) $((secs%86400/3600)) $((secs%3600/60)) \
$((secs%60))
2d:17h:42m:1s
With nanoseconds
$ secs=21218.6474912
$ printf '%02dh:%02dm:%02fs\n' $(echo -e "$secs/3600\n$secs%3600/60\n$secs%60"| bc)
05h:53m:38.647491s
Based on https://stackoverflow.com/a/28451379/188159 but edit got rejected.
#!/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
}