Last active
August 29, 2015 14:03
-
-
Save genba/dad5df52b136b662d580 to your computer and use it in GitHub Desktop.
format_duration
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 format_duration(seconds): | |
""" | |
Format a duration given in seconds as a string expressing the number of hours, minutes and seconds | |
:param seconds: duration in seconds | |
:type seconds: int or float | |
:returns: str | |
""" | |
minutes = int(seconds / 60) | |
if minutes > 0: | |
seconds = seconds - minutes * 60 | |
hours = int(minutes / 60) | |
if hours > 0: | |
minutes = minutes - hours * 60 | |
strings = [] | |
if hours == 1: # singular | |
strings.append('{0} hour'.format(hours)) | |
elif hours > 0: # plural | |
strings.append('{0} hours'.format(hours)) | |
if minutes == 1: # singular | |
strings.append('{0} minute'.format(minutes)) | |
elif minutes > 0: # plural | |
strings.append('{0} minutes'.format(minutes)) | |
if seconds == 1: # singular | |
strings.append('{0} second'.format(seconds)) | |
else: # plural | |
strings.append('{0} seconds'.format(seconds)) | |
return ' '.join(strings) |
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 format_duration(seconds, format='compressed'): | |
""" | |
Format a duration given in seconds as a string expressing the number of hours, minutes and seconds | |
:param seconds: duration in seconds | |
:type seconds: int or float | |
:param format: format (compressed, verbose) | |
:returns: str | |
""" | |
import datetime | |
if format == 'compressed': | |
delta = datetime.timedelta(seconds=seconds) | |
return str(delta) | |
else: | |
minutes = int(seconds / 60) | |
if minutes > 0: | |
seconds = seconds - minutes * 60 | |
hours = int(minutes / 60) | |
if hours > 0: | |
minutes = minutes - hours * 60 | |
strings = [] | |
if hours == 1: # singular | |
strings.append('{0} hour'.format(hours)) | |
elif hours > 0: # plural | |
strings.append('{0} hours'.format(hours)) | |
if minutes == 1: # singular | |
strings.append('{0} minute'.format(minutes)) | |
elif minutes > 0: # plural | |
strings.append('{0} minutes'.format(minutes)) | |
if seconds == 1: # singular | |
strings.append('{0} second'.format(seconds)) | |
else: # plural | |
strings.append('{0} seconds'.format(seconds)) | |
return ' '.join(strings) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment