Skip to content

Instantly share code, notes, and snippets.

@mesmerx
Last active August 1, 2020 02:31
Show Gist options
  • Save mesmerx/eb65e09e28d0780eb186ac22827cc39f to your computer and use it in GitHub Desktop.
Save mesmerx/eb65e09e28d0780eb186ac22827cc39f to your computer and use it in GitHub Desktop.
codewars
from datetime import timedelta
def format_duration(seconds):
if not seconds:
return 'now'
timedelta_format = f"{timedelta(seconds=seconds)}"
hours, minutes, seconds = timedelta_format.split(":")
dict_of_time = {'hours': hours,
'minutes': minutes,
'seconds': seconds}
if "," in hours:
days, _, hours = hours.split(" ")
years, days = divmod(int(days), 365)
dict_of_time = {'years': years,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds}
array_of_time = [f'{int(value)} {interval if int(value)>1 else interval[:-1]}' for interval,
value in dict_of_time.items() if int(value)]
if len(array_of_time) == 1:
return array_of_time[0]
else:
array_of_time.insert(len(array_of_time)-1, ' and')
return ", ".join(array_of_time[:-2])+' '.join(array_of_time[-2:])
print(format_duration(100000))
print(format_duration(100000000))
print(format_duration(111))
print(format_duration(11))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment