A compilation of documentation   { en , fr }

Convert seconds to hours in bash

Tag:
Created on:
Last edited on:
Author:
Xavier Béguin

Below is a little shell function (whose principle I've found on the web, because I'm lazy – and that I decided to publish here to easily find it again) to naively convert a number of seconds to hours, minutes and seconds (the calculation of a number of days can be trivially added if needed):

seconds2human() {
    sec="$1"
    h=$((sec / 3600)) m=$(((sec % 3600) / 60)) s=$((sec % 60))
    printf "%2dh %02dm %02ds\n" $h $m $s
}

Note that this function is POSIX-compatible and could therefore be used in any command-line interpreter that implements this standard.

Here is en example of its usage:

$ seconds2human 12345
 3h 25m 45s 

Just for the sake of verification, let's test it on a easily recognizable number (24 h × 60 min × 60 sec = 86400 sec) :

$ seconds2human 86461
24h 01m 01s