diff --git a/satella/coding/structures/dictionaries/cache_dict.py b/satella/coding/structures/dictionaries/cache_dict.py index e6ebb4f16ad53f38b25c961d8a92e540cba45489..89cedc6809754dad305e74dd1d40e92e57db1974 100644 --- a/satella/coding/structures/dictionaries/cache_dict.py +++ b/satella/coding/structures/dictionaries/cache_dict.py @@ -11,6 +11,39 @@ from satella.coding.typing import K, V, NoArgCallable logger = logging.getLogger(__name__) +_TIME_MODIFIERS = [ + ('s', 1), + ('m', 60), + ('h', 60 * 60), + ('d', 24 * 60 * 60), + ('w', 7 * 24 * 60 * 60) +] +def _parse_time_string(s: tp.Union[int, float, str]) -> float: + """ + Parse a time string into seconds, so eg. '30m' will be equal to 1800, and so will + be '30 min'. + + This will correctly parse: + - seconds + - minutes + - hours + - days + - weeks + + .. warning:: This does not handle fractions of a second! + + :param s: time string or time value in seconds + :return: value in seconds + """ + if isinstance(s, (int, float)): + return s + + for modifier, multiple in _TIME_MODIFIERS: + if modifier in s: + return float(s[:s.index(modifier)]) * multiple + + return float(s) + class CacheDict(tp.Mapping[K, V]): """