Add Sleep duration string.

This commit is contained in:
Christopher Charbonneau Wells 2017-08-13 11:20:09 -04:00
parent cafbe048cb
commit 7e0b81960f
3 changed files with 35 additions and 6 deletions

View File

@ -22,4 +22,4 @@ class BabySerializer(serializers.HyperlinkedModelSerializer):
class SleepSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Sleep
fields = ('baby', 'start', 'end')
fields = ('baby', 'start', 'end', 'duration')

View File

@ -14,5 +14,5 @@ class BabyAdmin(admin.ModelAdmin):
@admin.register(Sleep)
class SleepAdmin(admin.ModelAdmin):
list_display = ('baby', 'start', 'end',)
list_display = ('baby', 'start', 'end', 'duration',)
search_fields = ('baby__first_name', 'baby__last_name',)

View File

@ -1,3 +1,9 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from math import floor
from django.db import models
@ -30,9 +36,32 @@ class Sleep(models.Model):
verbose_name_plural = 'Sleep'
def __str__(self):
return '{} slept from {} to {} on {}'.format(
return '{} slept for {}'.format(
self.baby,
self.start.time(),
self.end.time(),
self.end.date(),
self.duration()
)
def duration(self):
diff = self.end - self.start
if diff.seconds < 60:
duration = '{} second{}'.format(
diff.seconds,
's' if diff.seconds > 1 else ''
)
elif diff.seconds < 3600:
duration = '{} minute{}, {} second{}'.format(
floor(diff.seconds / 60),
's' if floor(diff.seconds / 60) > 1 else '',
diff.seconds % 60,
's' if diff.seconds % 60 > 1 else ''
)
else:
duration = '{} hour{}, {} minute{}, {} second{}'.format(
floor(diff.seconds / 3600),
's' if floor(diff.seconds / 3600) > 1 else '',
floor((diff.seconds - 3600) / 60),
's' if floor((diff.seconds - 3600) / 60) > 1 else '',
diff.seconds % 60,
's' if diff.seconds % 60 > 1 else ''
)
return duration