Commits

Matthew Schinckel  committed f85ff8e Merge

Merge

  • Participants
  • Parent commits c29d186, d7c1fb6

Comments (0)

Files changed (3)

File timedelta/helpers.py

     
     return sep.join(result)
 
+def iso8601_repr(timedelta):
+    """
+    Represent a timedelta as an ISO8601 duration.
+    http://en.wikipedia.org/wiki/ISO_8601#Durations
+
+    >>> from datetime import timedelta as td
+    >>> iso8601_repr(td(days=1, hours=2, minutes=3, seconds=4))
+    'P1DT2HM3S4'
+    """
+    years = timedelta.days / 365
+    weeks = (timedelta.days % 365) / 7
+    days = timedelta.days % 7
+
+    hours = timedelta.seconds / 3600
+    minutes = (timedelta.seconds % 3600) / 60
+    seconds = timedelta.seconds % 60
+
+    formatting = {'P': {'Y': years,
+                        'W': weeks,
+                        'D': days
+                        },
+                  'T': {'H': hours,
+                        'M': minutes,
+                        'S': seconds
+                        }
+                  }
+
+    result = ''
+    for category, subcats  in formatting.items():
+        result += category
+        for format, value in subcats.items():
+            if value:
+                result += '%d%c' % (value, format)
+
+    return result
+
 def parse(string):
     """
     Parse a string into a timedelta object.

File timedelta/templatetags/timedelta.py

 register = template.Library()
 
 # Don't really like using relative imports, but no choice here!
-from ..helpers import nice_repr
+from ..helpers import nice_repr, iso8601_repr
 
 @register.filter(name='timedelta')
 def timedelta(value, display="long"):
-    return nice_repr(value, display)
+    return nice_repr(value, display)
+
+@register.filter(name='iso8601')
+def iso8601(value):
+    return iso8601_repr(value)

File timedelta/widgets.py

         if initial in ["", None] or data in ["", None]:
             return True
         
-        if not isinstance(initial, datetime.timedelta):
-            initial = parse(initial)
+        if initial:
+            if not isinstance(initial, datetime.timedelta):
+                initial = parse(initial)
+
         if not isinstance(data, datetime.timedelta):
             data = parse(data)
         
-        return initial != data
+        return initial != data