mybuddy/core/utils.py

59 lines
1.7 KiB
Python
Raw Normal View History

2017-08-13 15:59:14 +00:00
# -*- coding: utf-8 -*-
2020-10-26 03:06:21 +00:00
from django.utils import timesince, timezone
from django.utils.translation import ngettext
2017-08-13 15:59:14 +00:00
2020-10-26 03:06:21 +00:00
def child_age_string(duration):
"""Monkey patch timesince function to day precision only.
"""
timesince.TIMESINCE_CHUNKS = (
(60 * 60 * 24 * 365, 'year'),
(60 * 60 * 24 * 30, 'month'),
(60 * 60 * 24 * 7, 'week'),
(60 * 60 * 24, 'day'),
)
return timesince.timesince(duration)
2017-10-30 18:26:49 +00:00
def duration_string(duration, precision='s'):
"""Format hours, minutes and seconds as a human-friendly string (e.g. "2
2017-10-30 18:26:49 +00:00
hours, 25 minutes, 31 seconds") with precision to h = hours, m = minutes or
s = seconds.
"""
h, m, s = duration_parts(duration)
duration = ''
if h > 0:
duration = ngettext('%(hours)s hour', '%(hours)s hours', h) % {
'hours': h
}
2017-10-30 18:26:49 +00:00
if m > 0 and precision != 'h':
if duration != '':
duration += ', '
2019-11-09 23:21:54 +00:00
duration += ngettext(
'%(minutes)s minute',
'%(minutes)s minutes',
m
) % {'minutes': m}
2017-10-30 18:26:49 +00:00
if s > 0 and precision != 'h' and precision != 'm':
if duration != '':
duration += ', '
2019-11-09 23:21:54 +00:00
duration += ngettext(
'%(seconds)s second',
'%(seconds)s seconds',
s
) % {'seconds': s}
return duration
def duration_parts(duration):
2017-10-30 18:26:49 +00:00
"""Get hours, minutes and seconds from a timedelta.
"""
if not isinstance(duration, timezone.timedelta):
raise TypeError('Duration provided must be a timedetla')
h, remainder = divmod(duration.seconds, 3600)
h += duration.days * 24
m, s = divmod(remainder, 60)
return h, m, s