Created
May 20, 2017 13:58
-
-
Save sodle/222155df86117d5c4ebcc2e272c1d233 to your computer and use it in GitHub Desktop.
Python function to express timedeltas verbally.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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