12

I want to display /proc/uptime in well format as:

DD:HH:MM:SS

/proc/uptime give me up time of system in seconds, is there a standard solution that convert seconds to this format?

5 Answers 5

18

Here's a way without perl:

awk '{printf("%d:%02d:%02d:%02d\n",($1/60/60/24),($1/60/60%24),($1/60%60),($1%60))}' /proc/uptime
0
6

You can do this for example with perl and some simple math:

cat /proc/uptime |  perl -ne '/(\d*)/ ; printf "%02d:%02d:%02d:%02d\n",int($1/86400),int(($1%86400)/3600),int(($1%3600)/60),$1%60' 

If you do not need the seconds, you can simply run the uptime command. Its output can then be simply transformed to DD:HH:MM.

For example using (works this way only if uptime > 1h)

 uptime | perl -ne '/(\d*) day[^\d]*(\d*):(\d*)/ ; printf "%02d:%02d:%02d\n", $1, $2, $3'
3

No, because it's not really a hard problem. Divide the number of seconds by 86400 using integer division to get the number of days. Take the remainder and divide that by 3600 to get the number of hours. Divide the remainder of that by 60 to get the number of minutes, and you're left with the number of seconds. All this is doable from the shell using the expr command if your shell is ancient enough to not support arithmetic natively

Taking the number of seconds since the epoch and turning that into a human readable date is a hard problem, and so there are standard ways to do that, e.g. date -r SECONDS from the shell. But that's a different problem.

3

Adapting the relevant part of this answer.

As long as your uptime is less than a year, you can use the following command:

TZ=UTC date -d@$(cut -d\  -f1 /proc/uptime) +'%j %T' | awk '{print $1-1"d",$2}'

I extract the first field of the uptime file, since at least on my Linux, there is a second field containing the total idle time. I treat that as the number of seconds since the epoch, and convert that to day of the year followed by time in hours, minutes and seconds. Since the day of the year starts at one, I subtract one from that in my final awk invocation.

2
$ s=12345678
$ printf '%d:%02d:%02d:%02d\n' $((s/86400)) $((s/3600%24)) $((s/60%60)) $((s%60))
142:21:21:18

Converting seconds since epoch to a date and time:

$ gdate -d @1234567890 '+%F %T' # GNU date
2009-02-14 01:31:30
$ date -r 1234567890 '+%F %T' # BSD date
2009-02-14 01:31:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .