From 150c07c701d47fad162d1dbeb8f478bfb7273854 Mon Sep 17 00:00:00 2001 From: iou1name Date: Mon, 30 Mar 2020 08:50:16 -0400 Subject: [PATCH] fix and refactor relative_time() --- tools.py | 49 +++++++++++++++++++------------------------------ 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/tools.py b/tools.py index 6caa8bc..8838c86 100755 --- a/tools.py +++ b/tools.py @@ -225,37 +225,26 @@ def relative_time(time_1, time_2): assert type(time_2) == datetime, "time_2 must be datetime object" diff = time_1 - time_2 - msg = [] + msg = "" + units = {} if diff.days >= 365: - if diff.days // 365 > 1: - msg.append(f"{diff.days // 365} years") - else: - msg.append(f"{diff.days // 365} year") + units['year'] = diff.days // 365 + if diff.days >= 0: + units['day'] = diff.days - units.get('year', 0)*365 - if diff.days: - if diff.days > 1: - msg.append(f"{diff.days - (diff.days // 365)*365} days") - else: - msg.append(f"{diff.days} - (diff.days // 365)*365 day") + if not any(units.values()): + if diff.seconds // 3600: + units['hour'] = diff.seconds // 3600 + if diff.seconds // 60: + units['minute'] = (diff.seconds - units.get('hour', 0)*3600) // 60 + if not units.get('hour'): + units['second'] = diff.seconds - units.get('minute', 0)*60 - if not msg: - if diff.hours: - if diff.hours > 1: - msg.append(f"{diff.hours} hours") - else: - msg.append(f"{diff.hours} hour") - - if diff.minutes: - if diff.minutes > 1: - msg.append(f"{diff.minutes} minutes") - else: - msg.append(f"{diff.minutes} minute") - - if not diff.hours: - if diff.seconds > 1: - msg.append(f"{diff.seconds} seconds") - else: - msg.append(f"{diff.seconds} second") - - msg = ", ".join(msg) + for unit, value in units.items(): + if value: + msg += str(value) + ' ' + unit + if value > 1: + msg += 's' + msg += ', ' + msg = msg[:-2] return msg