DIVS = [86400 * 365, 86400, 3600, 60] def eval_time(a, b, c): if a >= DIVS[b]: c.append(a // DIVS[b]) else: c.append(0) remain = a % DIVS[b] if (remain > 0) and (b < 3): eval_time(remain, b + 1, c) else: c.append(remain) def pretty_output(a): names = [" year", " day", " hour", " minute", " second"] r = "" for i in range(0, len(a)): if a[i] >= 1: r += str(a[i]) + names[i] if a[i] > 1: r += "s" r += ", " r = r.strip(", ") s_items = r.rsplit(",") if len(s_items) > 1: print(",".join(s_items[:-1]) + " and" + s_items[-1]) elif s_items[0] == "": print("now") else: print(r) def format_duration(n): time_vals = [] eval_time(n, 0, time_vals) pretty_output(time_vals) format_duration(62) format_duration(3662) format_duration(66711841) format_duration(31539601) format_duration(120) format_duration(0)
1 minute and 2 seconds 1 hour, 1 minute and 2 seconds 2 years, 42 days, 3 hours, 4 minutes and 1 second 1 year, 1 hour and 1 second 2 minutes now
The pretty_output method was more challenging than I first thought, I did get a bit lazy with the if/elif/else statements
pretty_output
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Python3
Solution
Output
The
pretty_output
method was more challenging than I first thought, I did get a bit lazy with the if/elif/else statements