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"
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