66 lines
1.4 KiB
Python
Executable File
66 lines
1.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Tools for working with time.
|
|
"""
|
|
from datetime import datetime
|
|
|
|
from dateutil.relativedelta import relativedelta
|
|
|
|
import config
|
|
|
|
|
|
def relativeTime(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.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
|