fulvia/tools/time.py

64 lines
1.4 KiB
Python
Raw Normal View History

2018-03-16 03:13:43 -04:00
#!/usr/bin/env python3
"""
Tools for working with time.
"""
from datetime import datetime
from dateutil.relativedelta import relativedelta
def relativeTime(config, time_1, time_2):
"""
Returns the relative time difference between 'time_1' and 'time_2'.
If either 'time_1' or 'time_2' is a string, it will be converted to a
datetime object according to the 'default_time_format' variable in the
config.
"""
t_format = config.core.default_time_format
if type(time_1) == str:
time_1 = datetime.strptime(time_1, t_format)
if type(time_2) == str:
time_2 = datetime.strptime(time_2, t_format)
msg = []
diff = relativedelta(time_1, time_2)
if diff.years:
if diff.years > 1:
msg.append(f"{diff.years} years")
else:
msg.append(f"{diff.years} year")
if diff.months:
if diff.months > 1:
msg.append(f"{diff.months} months")
else:
msg.append(f"{diff.months} month")
if diff.days:
if diff.days > 1:
msg.append(f"{diff.days} days")
else:
msg.append(f"{diff.days} day")
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)
return msg