Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python function to express timedeltas verbally.
def verbal_timedelta(td):
"""Expresses a Python timedelta verbally
:param td: A Python timedelta
:type td: timedelta
:return: A verbal description of the time relative to now
:rtype: str"""
if td.days != 0:
abs_days = abs(td.days)
if abs_days > 7:
abs_delta = '{} weeks'.format(td.days // 7)
else:
abs_delta = '{} days'.format(td.days)
else:
abs_minutes = abs(td.seconds) // 60
if abs_minutes > 60:
abs_delta = '{} hours'.format(abs_minutes // 60)
else:
abs_delta = '{} minutes'.format(abs_minutes)
if td < timedelta(0):
return '{} ago'.format(abs_delta)
else:
return 'in {}'.format(abs_delta)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment