src/pyams_catalog/index.py
changeset 8 e31e81bcf6dd
parent 0 15b51dd45bab
child 22 8c121a145dbe
--- a/src/pyams_catalog/index.py	Wed May 20 12:21:20 2015 +0200
+++ b/src/pyams_catalog/index.py	Wed Jun 17 09:55:43 2015 +0200
@@ -14,8 +14,10 @@
 
 
 # import standard library
+from datetime import date, datetime
 
 # import interfaces
+from pyams_catalog.interfaces import NO_RESOLUTION, DATE_RESOLUTION
 
 # import packages
 from hypatia.facet import FacetIndex
@@ -52,7 +54,7 @@
             if callable(value):
                 value = value(obj)
 
-        if value is _marker:
+        if (value is None) or (value is _marker):
             return default
 
         if isinstance(value, Persistent):
@@ -72,6 +74,37 @@
         FieldIndex.__init__(self, discriminator, family)
 
 
+def get_resolution(value, resolution):
+    """Set resolution of given date or datetime"""
+    if not value:
+        return value
+    if resolution < NO_RESOLUTION:
+        args = []
+        if isinstance(value, date):
+            resolution = max(resolution, DATE_RESOLUTION)
+        args.extend(value.timetuple()[:resolution+1])
+        if isinstance(value, date):
+            args.extend([0] * (2 - resolution))
+            value = date(*args)
+        else:
+            args.extend([0] * (5 - resolution))
+            args.append(value.tzinfo)
+            value = datetime(*args)
+        return value
+
+
+class DatetimeIndexWithInterface(FieldIndexWithInterface):
+    """Normalized datetime index with interface support"""
+
+    def __init__(self, interface, discriminator, resolution=DATE_RESOLUTION, family=None):
+        FieldIndexWithInterface.__init__(self, interface, discriminator, family)
+        self.resolution = resolution
+
+    def discriminate(self, obj, default):
+        value = super(DatetimeIndexWithInterface, self).discriminate(obj, default)
+        return get_resolution(value, self.resolution)
+
+
 class KeywordIndexWithInterface(InterfaceSupportIndexMixin, KeywordIndex):
     """Keyword index with interface support"""