User Tools

Site Tools


hacks:appx-uptime.py

appx-uptime.py

This project has been superseded by a Go implementation found here.

Original script

Figure out the approximate uptime of a Linux host in plain English without crazy libraries.

#!/usr/bin/env python
#
# appx-uptime.py - a silly script to figure out plain English uptime
#
# Copyright (c) 2015 Gabriel M. O'Brien
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
 
from datetime import datetime, timedelta
 
with open('/proc/uptime', 'r') as f:
    uptime_sec = int(float(f.readline().split()[0]))
 
f.close()
 
# convert to human time
uptime_min = uptime_sec / 60
uptime_hour = uptime_min / 60
dd = uptime_hour / 24
 
# calculate remainders
mm = uptime_min % 60
mm = mm - mm % 10
hh = uptime_hour % 24
 
# set units string
d_str = "day"
h_str = "hour"
m_str = "minutes"
 
# pluralize units if required
if dd != 1: d_str = d_str + "s"
if hh != 1: h_str = h_str + "s"
 
# print nice old time string based on case
if dd == 0:
    if hh == 0:
        if mm == 0:
            print "a few minutes"
        else:
            print("about %s %s" % (mm, m_str))
    else:
        if mm == 0:
            print("about %s %s" % (hh, h_str))
        else:
            print("about %s %s and %s %s" % (hh, h_str, mm, m_str))
else:
    if hh == 0:
        if mm == 0:
            print("about %s %s" % (dd, d_str))
        else:
            print("about %s %s and %s %s" % (dd, d_str, mm, m_str))
    else:
        if mm == 0:
            print("about %s %s and %s %s" % (dd, d_str, hh, h_str))
        else:
            print("about %s %s, %s %s, and %s %s" % (dd, d_str, hh, h_str, mm, m_str))
 
hacks/appx-uptime.py.txt · Last modified: 2019-08-10 14:54 by gabriel