added nicely readable (approx.) time converter

This commit is contained in:
2020-11-23 18:42:16 +01:00
parent 53cef59ce5
commit e659831492
2 changed files with 32 additions and 0 deletions
+1
View File
@@ -8,6 +8,7 @@ from .json import json_save, json_load
from .npy import nice_linspace, nice_arange, fraction_to_percentage, within, within_fraction, get_dtype, get_shape, is_array
from .path import can_create_all_files, can_create_file, glob_files, make_missing_dir
from .pv import PV
from .readable import readable_seconds
from .screenshot import Screenshot
+31
View File
@@ -0,0 +1,31 @@
AVERAGE_WEEKS_PER_MONTH = 365.242 / 12 / 7
# each tuple gives a unit and the number of previous units which go into it
UNITS = (
("minute", 60),
("hour", 60),
("day", 24),
("week", 7),
("month", AVERAGE_WEEKS_PER_MONTH),
("year", 12)
)
def readable_seconds(secs):
# adapted from https://stackoverflow.com/a/18421524/655404
unit, number = "second", float(abs(secs))
for next_unit, ratio in UNITS:
next_number = number / ratio
# if the next number is small, don't go to the next unit.
if next_number < 2:
break
unit, number = next_unit, next_number
shown = int(round(number))
unit += "" if shown == 1 else "s"
return f"{shown} {unit}"