Add a short param to the duration_string for XhXmXs formatted durations.

This commit is contained in:
Christopher Charbonneau Wells 2017-08-16 19:08:52 -04:00
parent 463dd0c1d7
commit 1185addace
3 changed files with 15 additions and 11 deletions

View File

@ -126,7 +126,8 @@ class Timer(models.Model):
return 'Timer ({})'.format(self.name)
def duration(self):
return duration_string(self.start, self.end or timezone.now())
return duration_string(self.start, self.end or timezone.now(),
short=True)
def save(self, *args, **kwargs):
self.active = self.end is None

View File

@ -1,3 +1,3 @@
{% for timer in timers %}
{{ timer.name }} ({{ timer.duration }})
{{ timer.name }} ({{ timer.duration }})<br/>
{% endfor %}

View File

@ -4,21 +4,24 @@ from __future__ import unicode_literals
from math import floor
def duration_string(start, end):
def duration_string(start, end, short=False):
diff = end - start
h = floor(diff.seconds / 3600)
m = floor((diff.seconds - h * 3600) / 60)
s = diff.seconds % 60
duration = ''
if h > 0:
duration = '{} hour{}'.format(h, 's' if h > 1 else '')
if m > 0:
duration += '{}{} minute{}'.format(
'' if duration is '' else ', ', m, 's' if m > 1 else '')
if s > 0:
duration += '{}{} second{}'.format(
'' if duration is '' else ', ', s, 's' if s > 1 else '')
if short:
duration = '{}h {}m {}s'.format(h, m, s)
else:
if h > 0:
duration = '{} hour{}'.format(h, 's' if h > 1 else '')
if m > 0:
duration += '{}{} minute{}'.format(
'' if duration is '' else ', ', m, 's' if m > 1 else '')
if s > 0:
duration += '{}{} second{}'.format(
'' if duration is '' else ', ', s, 's' if s > 1 else '')
return duration