Timify routine for Python3

Takes a number of seconds i.e. “120000002” and converts into “3y 42w 2d 21h 20m 2s”.

#!/usr/bin/python3

def timeify(seconds):
    from collections import OrderedDict
    from math import floor

    units = dict()
    units["s"] = 1
    units["m"] = 60
    units["h"] = 60 * units["m"]
    units["d"] = 24 * units["h"]
    units["w"] = 7 * units["d"]
    units["y"] = 52 * units["w"]

    result = []
    for unit in reversed(units):
        if (s:=floor(seconds / units[unit])) != 0:
                result.append(str(s)+unit)
                seconds = seconds - s * units[unit];

    return (" ".join(result))

print (timeify(120000002));
Dette indlæg blev udgivet i Python. Bogmærk permalinket.