fix and refactor relative_time()

This commit is contained in:
iou1name 2020-03-30 08:50:16 -04:00
parent ac1ecdfc44
commit 150c07c701

View File

@ -225,37 +225,26 @@ def relative_time(time_1, time_2):
assert type(time_2) == datetime, "time_2 must be datetime object" assert type(time_2) == datetime, "time_2 must be datetime object"
diff = time_1 - time_2 diff = time_1 - time_2
msg = [] msg = ""
units = {}
if diff.days >= 365: if diff.days >= 365:
if diff.days // 365 > 1: units['year'] = diff.days // 365
msg.append(f"{diff.days // 365} years") if diff.days >= 0:
else: units['day'] = diff.days - units.get('year', 0)*365
msg.append(f"{diff.days // 365} year")
if diff.days: if not any(units.values()):
if diff.days > 1: if diff.seconds // 3600:
msg.append(f"{diff.days - (diff.days // 365)*365} days") units['hour'] = diff.seconds // 3600
else: if diff.seconds // 60:
msg.append(f"{diff.days} - (diff.days // 365)*365 day") 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: for unit, value in units.items():
if diff.hours: if value:
if diff.hours > 1: msg += str(value) + ' ' + unit
msg.append(f"{diff.hours} hours") if value > 1:
else: msg += 's'
msg.append(f"{diff.hours} hour") msg += ', '
msg = msg[:-2]
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)
return msg return msg