diff --git a/slic/utils/__init__.py b/slic/utils/__init__.py index 36adc91c7..19e640441 100644 --- a/slic/utils/__init__.py +++ b/slic/utils/__init__.py @@ -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 diff --git a/slic/utils/readable.py b/slic/utils/readable.py new file mode 100644 index 000000000..5f72b7462 --- /dev/null +++ b/slic/utils/readable.py @@ -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}" + + +