Commits

Felipe Prenholato committed 1ad5972

Add i18n support, pt_BR translations, filter as_hours and fix some PEP8 errors.

Comments (0)

Files changed (4)

timedelta/helpers.py

 import re
 import datetime
 from decimal import Decimal
+from django.utils.translation import ungettext as __, ugettext_lazy as _
+
+def get_words(display='long'):
+    """
+    TODO: make docts
+    """
+    words = {
+        'minimal': [
+            lambda c: _("w"), lambda c: _("d"), lambda c: _("h"),
+            lambda c: _("m"), lambda c: _("s")],
+        'short': [
+            lambda c: __(" wk", " wks", c), lambda c: __(" day", " days", c),
+            lambda c: __(" hr", " hrs", c), lambda c: _(" min"),
+            lambda c: _(" sec")],
+        'long': [
+            lambda c: __(" week", " weeks", c), lambda c: __(" day", " days", c),
+            lambda c: __(" hour", " hours", c),
+            lambda c: __(" minute", " minutes", c),
+            lambda c: __(" second", " seconds", c)]
+        }
+    return words[display]
 
 def nice_repr(timedelta, display="long", sep=", "):
     """
     Turns a datetime.timedelta object into a nice string repr.
-    
+
     display can be "minimal", "short" or "long" [default].
-    
+
     >>> from datetime import timedelta as td
     >>> nice_repr(td(days=1, hours=2, minutes=3, seconds=4))
-    '1 day, 2 hours, 3 minutes, 4 seconds'
+    u'1 day, 2 hours, 3 minutes, 4 seconds'
     >>> nice_repr(td(days=1, seconds=1), "minimal")
-    '1d, 1s'
+    u'1d, 1s'
     """
-    
+
     assert isinstance(timedelta, datetime.timedelta), "First argument must be a timedelta."
-    
+
     result = []
-    
+
     weeks = timedelta.days / 7
     days = timedelta.days % 7
     hours = timedelta.seconds / 3600
     minutes = (timedelta.seconds % 3600) / 60
     seconds = timedelta.seconds % 60
-    
+
     if display == "sql":
         days += weeks * 7
         return "%i %02i:%02i:%02i" % (days, hours, minutes, seconds)
-    elif display == 'minimal':
-        words = ["w", "d", "h", "m", "s"]
-    elif display == 'short':
-        words = [" wks", " days", " hrs", " min", " sec"]
     else:
-        words = [" weeks", " days", " hours", " minutes", " seconds"]
-    
+        words = get_words(display, )
+
     values = [weeks, days, hours, minutes, seconds]
-    
+
     for i in range(len(values)):
         if values[i]:
-            if values[i] == 1 and len(words[i]) > 1:
-                result.append("%i%s" % (values[i], words[i].rstrip('s')))
-            else:
-                result.append("%i%s" % (values[i], words[i]))
-    
+            result.append(u"%i%s" % (values[i], words[i](values[i])))
+
+    return sep.join(result)
+
+def as_hours(timedelta, display='long', sep=', '):
+    """
+    Turns a datetime.timedelta object into a nice string repr with hours,
+    minutes and seconds.
+
+    display can be "minimal", "short" or "long" [default].
+
+    >>> from datetime import timedelta as td
+    >>> from django.utils import translation
+    >>> translation.activate('pt_BR')
+    >>> as_hours(td(days=1, hours=2, minutes=3, seconds=4))
+    u'26 horas, 3 minutos, 4 segundos'
+    >>> as_hours(td(days=1, seconds=1), "minimal")
+    u'24h, 1s'
+    >>> translation.activate('en_us')
+    >>> as_hours(td(days=1, hours=2, minutes=3, seconds=4))
+    u'26 hours, 3 minutes, 4 seconds'
+    >>> as_hours(td(days=1, seconds=1), "minimal")
+    u'24h, 1s'
+    >>> as_hours(td(hours=1, seconds=1))
+    u'1 hour, 1 second'
+    >>> as_hours(td(hours=1, seconds=2))
+    u'1 hour, 2 seconds'
+    >>> as_hours(td(hours=1, minutes=61, seconds=2))
+    u'2 hours, 1 minute, 2 seconds'
+
+    """
+
+    assert isinstance(timedelta, datetime.timedelta), "First argument must be a timedelta."
+
+    result = []
+
+    hours = int(timedelta.total_seconds() / 3600)
+    minutes = int((timedelta.total_seconds() % 3600)) / 60
+    seconds = int(timedelta.total_seconds() % 60)
+
+    if display == "sql":
+        return "%02i:%02i:%02i" % (hours, minutes, seconds)
+    else:
+        words = get_words(display, )
+
+    values = [0, 0, hours, minutes, seconds]
+
+    for i in range(len(values)):
+        if values[i]:
+            result.append(u"%i%s" % (values[i], words[i](values[i])))
+
     return sep.join(result)
 
 def iso8601_repr(timedelta):
 def parse(string):
     """
     Parse a string into a timedelta object.
-    
+
     >>> parse("1 day")
     datetime.timedelta(1)
     >>> parse("2 days")
     Traceback (most recent call last):
     ...
     TypeError: '' is not a valid time interval
-    
+
     """
     if string == "":
         raise TypeError("'%s' is not a valid time interval" % string)
     d = re.match(r'((?P<days>\d+) days?,? )?(?P<hours>\d+):'
                  r'(?P<minutes>\d+)(:(?P<seconds>\d+))?',
                  unicode(string))
-    if d: 
+    if d:
         d = d.groupdict(0)
     else:
         # This is the more flexible format
         if not d:
             raise TypeError("'%s' is not a valid time interval" % string)
         d = d.groupdict(0)
-    
+
     return datetime.timedelta(**dict(( (k, float(v)) for k,v in d.items())))
 
 
     """
     Allows for the division of timedeltas by other timedeltas, or by
     floats/Decimals
-    
+
     >>> from datetime import timedelta as td
     >>> divide(td(1), td(1))
     1
     """
     assert isinstance(obj1, datetime.timedelta), "First argument must be a timedelta."
     assert isinstance(obj2, (datetime.timedelta, int, float, Decimal)), "Second argument must be a timedelta or number"
-    
+
     sec1 = obj1.days * 86400 + obj1.seconds
     if isinstance(obj2, datetime.timedelta):
         sec2 = obj2.days * 86400 + obj2.seconds
 def modulo(obj1, obj2):
     """
     Allows for remainder division of timedelta by timedelta or integer.
-    
+
     >>> from datetime import timedelta as td
     >>> modulo(td(5), td(2))
     datetime.timedelta(1)
     """
     assert isinstance(obj1, datetime.timedelta), "First argument must be a timedelta."
     assert isinstance(obj2, (datetime.timedelta, int)), "Second argument must be a timedelta or int."
-    
+
     sec1 = obj1.days * 86400 + obj1.seconds
     if isinstance(obj2, datetime.timedelta):
         sec2 = obj2.days * 86400 + obj2.seconds
         return datetime.timedelta(seconds=sec1 % sec2)
     else:
         return datetime.timedelta(seconds=(sec1 % obj2))
-    
+
 def percentage(obj1, obj2):
     """
     What percentage of obj2 is obj1? We want the answer as a float.
     """
     assert isinstance(obj1, datetime.timedelta), "First argument must be a timedelta."
     assert isinstance(obj2, datetime.timedelta), "Second argument must be a timedelta."
-    
+
     return divide(obj1 * 100, obj2, as_float=True)
 
 def decimal_percentage(obj1, obj2):
     Decimal('50.0')
     """
     return Decimal(str(percentage(obj1, obj2)))
-    
-    
+
+
 def multiply(obj, val):
     """
     Allows for the multiplication of timedeltas by float values.
     >>> multiply(datetime.timedelta(seconds=20), 1.5)
     datetime.timedelta(0, 30)
     """
-    
+
     assert isinstance(obj, datetime.timedelta), "First argument must be a timedelta."
     assert isinstance(val, (int, float, Decimal)), "Second argument must be a number."
-    
+
     sec = obj.days * 86400 + obj.seconds
     sec *= val
     if isinstance(sec, Decimal):
 def round_to_nearest(obj, timedelta):
     """
     The obj is rounded to the nearest whole number of timedeltas.
-    
+
     obj can be a timedelta, datetime or time object.
-    
+
     >>> round_to_nearest(datetime.datetime(2012, 1, 1, 9, 43), datetime.timedelta(1))
     datetime.datetime(2012, 1, 1, 0, 0)
     >>> round_to_nearest(datetime.datetime(2012, 1, 1, 9, 43), datetime.timedelta(hours=1))
     >>> round_to_nearest(datetime.datetime(2012, 1, 1, 9, 43), datetime.timedelta(minutes=1))
     datetime.datetime(2012, 1, 1, 9, 43)
     """
-    
+
     assert isinstance(obj, (datetime.datetime, datetime.timedelta, datetime.time)), "First argument must be datetime, time or timedelta."
     assert isinstance(timedelta, datetime.timedelta), "Second argument must be a timedelta."
-    
+
     time_only = False
     if isinstance(obj, datetime.timedelta):
         counter = datetime.timedelta(0)
         counter = datetime.datetime.combine(datetime.date.today(), datetime.time(0, tzinfo=obj.tzinfo))
         obj = datetime.datetime.combine(datetime.date.today(), obj)
         time_only = True
-    
+
     diff = abs(obj - counter)
     while counter < obj:
         old_diff = diff
         counter += timedelta
         diff = abs(obj - counter)
-    
+
     if counter == obj:
         result = obj
     elif diff <= old_diff:
         result = counter
     else:
         result = counter - timedelta
-    
+
     if time_only:
         return result.time()
     else:
 def week_containing(date):
     if date.weekday():
         date -= datetime.timedelta(date.weekday())
-    
+
     return date, date + datetime.timedelta(6)
 
 try:

timedelta/locale/pt_BR/LC_MESSAGES/django.mo

Binary file added.

timedelta/locale/pt_BR/LC_MESSAGES/django.po

+# pt_BR translaton for django-timedelta-field.
+# Copyright (C) 2012
+# This file is distributed under the same license as the django-timedelta-field package.
+# Felipe Prenholato <philipe.rp@gmail.com>, 2012.
+msgid ""
+msgstr ""
+"Project-Id-Version: 0.6.7\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: 2012-10-26 11:20-0200\n"
+"PO-Revision-Date: 2012-10-26 11:20-0200\n"
+"Last-Translator: Felipe Prenholato <philipe.rp@gmail.com>\n"
+"Language-Team: Felipe Prenholato <philipe.rp@gmail.com>\n"
+"Language: pt_BR\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=(n > 1)\n"
+
+#: forms.py:12
+msgid "Enter a valid time span: e.g. \"3 days, 4 hours, 2 minutes\""
+msgstr "Entre um intervalo de tempo válido: ex \"3 days, 4 hours, 2 minutes\""
+
+
+#: helpers.py:12
+msgid "w"
+msgstr ""
+
+#: helpers.py:12
+msgid "d"
+msgstr ""
+
+#: helpers.py:12
+msgid "h"
+msgstr ""
+
+#: helpers.py:13
+msgid "m"
+msgstr ""
+
+#: helpers.py:13
+msgid "s"
+msgstr ""
+
+#: helpers.py:15
+msgid " wk"
+msgstr " sem"
+
+#: helpers.py:15 helpers.py:19
+msgid " day"
+msgid_plural " days"
+msgstr[0] " dia"
+msgstr[1] " dias"
+
+#: helpers.py:16
+msgid " hr"
+msgstr ""
+
+#: helpers.py:16
+msgid " min"
+msgstr ""
+
+#: helpers.py:17
+msgid " sec"
+msgstr " seg"
+
+#: helpers.py:19
+msgid " week"
+msgid_plural " weeks"
+msgstr[0] " semana"
+msgstr[1] " semanas"
+
+#: helpers.py:20
+msgid " hour"
+msgid_plural " hours"
+msgstr[0] " hora"
+msgstr[1] " horas"
+
+#: helpers.py:21
+msgid " minute"
+msgid_plural " minutes"
+msgstr[0] " minuto"
+msgstr[1] " minutos"
+
+#: helpers.py:22
+msgid " second"
+msgid_plural " seconds"
+msgstr[0] " segundo"
+msgstr[1] " segundos"

timedelta/templatetags/timedelta.py

 register = template.Library()
 
 # Don't really like using relative imports, but no choice here!
-from ..helpers import nice_repr, iso8601_repr, total_seconds as _total_seconds
+from ..helpers import (nice_repr, iso8601_repr, total_seconds as _total_seconds,
+    as_hours as _as_hours)
 
 @register.filter(name='timedelta')
 def timedelta(value, display="long"):
     return _total_seconds(value)
 
 @register.filter(name='total_seconds_sort')
-def total_seconds(value, places=10):
+def total_seconds_sort(value, places=10):
     return ("%0" + str(places) + "i") % _total_seconds(value)
 
+@register.filter(name='as_hours')
+def as_hours(value, display="long"):
+    return _as_hours(value, display=display)