Replace the date, datetime or period tuples in obj.value with
        appropriate strings.
323727
def transformFromNative(obj):
        
        if obj.value and type(obj.value[0]) == datetime.date:
            obj.isNative = False
            obj.value_param = 'DATE'
            obj.value = ','.join([dateToString(val) for val in obj.value])
            return obj
        # Fixme: handle PERIOD case
        else:
            if obj.isNative:
                obj.isNative = False
                transformed = []
                tzid = None
                for val in obj.value:
                    if tzid is None and type(val) == datetime.datetime:
                        tzid = TimezoneComponent.registerTzinfo(val.tzinfo)
                        if tzid is not None:
                            obj.tzid_param = tzid
                    transformed.append(dateTimeToString(val))
                obj.value = ','.join(transformed)
            return obj
414390
def stringify(self, value):
        
        # SuperModel -> UID
        if ISuperModel.providedBy(value):
            return str(value)
        # DateTime -> ISO8601 format
        elif isinstance(value, (DateTime)):
            return value.ISO8601()
        # Image/Files -> filename
        elif safe_hasattr(value, "filename"):
            return value.filename
        # Dict -> convert_value_to_string
        elif isinstance(value, dict):
            return {k: self.stringify(v) for k, v in value.iteritems()}
        # List -> convert_value_to_string
        if isinstance(value, (list, tuple, LazyMap)):
            return map(self.stringify, value)
        # Callables
        elif safe_callable(value):
            return self.stringify(value())
        elif isinstance(value, unicode):
            value = value.encode("utf8")
        try:
            return str(value)
        except (AttributeError, TypeError, ValueError):
            logger.warn("Could not convert {} to string".format(repr(value)))
            return None
705553
def prepare(cls, value):
        """"""
        pfield = struct.pack('b', cls.type_code)
        if isinstance(value, string_types):
            if "." in value:
                value = datetime.datetime.strptime(value, "%H:%M:%S.%f")
            else:
                value = datetime.datetime.strptime(value, "%H:%M:%S")
        millisecond = value.second * 1000 + value.microsecond // 1000
        hour = value.hour | 0x80    # for some unknown reasons hour has to be bit-or'ed with 0x80
        pfield += cls._struct.pack(hour, value.minute, millisecond)
        return pfield
1374815
def _convert(value, tzto, defaulttz):
    """"""
    if not isinstance(value, datetime):
        raise ValueError('value must be a datetime.datetime object')

    if value.tzinfo is None:
        value = value.replace(tzinfo=defaulttz)

    return value.astimezone(tzto)
525698
def _serialize_value(self, value):
        
        if isinstance(value, (list, tuple, set)):
            return [self._serialize_value(v) for v in value]
        elif isinstance(value, dict):
            return dict([(k, self._serialize_value(v)) for k, v in value.items()])
        elif isinstance(value, ModelBase):
            return value._serialize()
        elif isinstance(value, datetime.date):  # includes datetime.datetime
            return value.isoformat()
        else:
            return value
281883
def parse_datetime(value):
    
    if not value:
        return None
    elif isinstance(value, datetime.datetime):
        return value
    return dateutil.parser.parse(value)
1093876
def replaceVariables(path, datetime=None, pathvars=None):
    """"""

    if datetime is None:
        datetime = time.gmtime()

    # if path variables are not given, set as empty list
    if pathvars is None:
        pathvars = [ ]

    # create an init path list to loop through
    if isinstance(path, list):
        path_list = path
    else:
        path_list = [ path ]

    # Set up the regex to search for variables
    regex = re.compile('\$\{(.*?)\}')

    # create a newpath list that will hold the 'cleaned' paths
    # with variables and strftime format directives replaced
    newpath_list = [ ]

    for p in path_list:
        # create temppath_list to be used a we work through the
        newpath_list.append(p)

        # Variable replacement
        # Find all the variables in path using the regex
        for k in regex.findall(p):
            # Check if the key is in path variables map
            if k in pathvars:
                # get the str or list of values
                v = pathvars[k]

                # Check value of variable must be in (string, integer, list)
                if type(v) is dict:
                    msg = "Path variable must refer to string, integer, or list"
                    raise TypeError(msg)

                # get the list of possible variable values
                value_list = v if type(v) is list else [ v ]


                # create temp_list for now
                temp_list = []

                # loop through the most recent newpath list
                # need to do this every time in order to account for all possible
                # combinations
                # replace the variables
                # loop through the list of values and replace the variables
                for v in value_list:
                    for newpath in newpath_list:
                        # remove the path from newpath_list
                        temp_list.append(newpath.replace('${%s}' % k, str(v)))

                # replace newpath_list
                newpath_list = temp_list

        # strftime translation
        # Loop through newpath_list to do strftime translation
        for index, newpath in enumerate(newpath_list):
            # Apply strftime translation
            newpath_list[index] = time.strftime(newpath, datetime)

    return newpath_list
274783
def _parse_date(self, cell_value):
    """"""
    date_tuple = xlrd.xldate_as_tuple(cell_value, self.raw_sheet.book.datemode)
    return self.tuple_to_datetime(date_tuple)
582366
def _to_python(self, value):
        
        if isinstance(value, (int, float, long, complex)):
            return value

        if isinstance(value, (list, tuple)):
            value = value[0]

        if value == 'true':
            return True
        elif value == 'false':
            return False

        is_string = False

        if IS_PY3:
            if isinstance(value, bytes):
                value = force_unicode(value)

            if isinstance(value, str):
                is_string = True
        else:
            if isinstance(value, str):
                value = force_unicode(value)

            if isinstance(value, basestring):  # NOQA: F821
                is_string = True

        if is_string:
            possible_datetime = DATETIME_REGEX.search(value)

            if possible_datetime:
                date_values = possible_datetime.groupdict()

                for dk, dv in date_values.items():
                    date_values[dk] = int(dv)

                return datetime.datetime(date_values['year'],
                                         date_values['month'],
                                         date_values['day'],
                                         date_values['hour'],
                                         date_values['minute'],
                                         date_values['second'])

        try:
            # This is slightly gross but it's hard to tell otherwise what the
            # string's original type might have been.
            return ast.literal_eval(value)
        except (ValueError, SyntaxError):
            # If it fails, continue on.
            pass

        return value
1340455
def string_to_date(value):
    
    if isinstance(value, datetime.date):
        return value

    return dateutil.parser.parse(value).date()
905237
def to_naive_datetime(self, value):
        
        if isinstance(value, (six.integer_types, float, six.string_types)):
            try:
                return self.from_number(value)
            except ValueError:
                return self.datetime_str_to_datetime(value)

        if isinstance(value, datetime.datetime):
            return value

        raise exceptions.ValidationError(
            "Unable to convert value: '%s' to python data type" % value,
            code="invalid_datetime"
        )
934893
def _json_safe(cls, value):
        """"""
        # Date
        if type(value) == date:
            return str(value)

        # Datetime
        elif type(value) == datetime:
            return value.strftime('%Y-%m-%d %H:%M:%S')

        # Object Id
        elif isinstance(value, ObjectId):
            return str(value)

        # Frame
        elif isinstance(value, _BaseFrame):
            return value.to_json_type()

        # Lists
        elif isinstance(value, (list, tuple)):
            return [cls._json_safe(v) for v in value]

        # Dictionaries
        elif isinstance(value, dict):
            return {k:cls._json_safe(v) for k, v in value.items()}

        return value
1293894
def valueFromString(self, value, context=None):
        
        if value in ('today', 'now'):
            return datetime.datetime.utcnow()
        elif dateutil_parser:
            return dateutil_parser.parse(value)
        else:
            time_struct = time.strptime(value, self.defaultFormat())
            return datetime.datetime(time_struct.tm_year,
                                     time_struct.tm_month,
                                     time_struct.tm_day,
                                     time_struct.tm_hour,
                                     time_struct.tm_minute,
                                     time_struct.tm_sec)
1257477
def _serialize(self, value, attr, obj):
        """"""
        try:
            return super(DateString, self)._serialize(
                arrow.get(value).date(), attr, obj)
        except ParserError:
            return missing
1154057
def clean_up_datetime(obj_map):
    """"""
    clean_map = {}
    for key, value in obj_map.items():
        if isinstance(value, datetime.datetime):
            clean_map[key] = {
                'year': value.year,
                'month': value.month,
                'day': value.day,
                'hour': value.hour,
                'minute': value.minute,
                'second': value.second,
                'microsecond': value.microsecond,
                'tzinfo': value.tzinfo
            }
        elif isinstance(value, dict):
            clean_map[key] = clean_up_datetime(value)
        elif isinstance(value, list):
            if key not in clean_map:
                clean_map[key] = []
            if len(value) > 0:
                for index, list_value in enumerate(value):
                    if isinstance(list_value, dict):
                        clean_map[key].append(clean_up_datetime(list_value))
                    else:
                        clean_map[key].append(list_value)
            else:
                clean_map[key] = value
        else:
            clean_map[key] = value
    return clean_map
1113840
def convert_value(self, v):
        

        def stringify(value):
            if self.encoding is not None:
                encoder = partial(pprint_thing_encoded,
                                  encoding=self.encoding)
            else:
                encoder = pprint_thing
            return encoder(value)

        kind = _ensure_decoded(self.kind)
        meta = _ensure_decoded(self.meta)
        if kind == 'datetime64' or kind == 'datetime':
            if isinstance(v, (int, float)):
                v = stringify(v)
            v = _ensure_decoded(v)
            v = Timestamp(v)
            if v.tz is not None:
                v = v.tz_convert('UTC')
            return TermValue(v, v.value, kind)
        elif kind == 'timedelta64' or kind == 'timedelta':
            v = Timedelta(v, unit='s').value
            return TermValue(int(v), v, kind)
        elif meta == 'category':
            metadata = com.values_from_object(self.metadata)
            result = metadata.searchsorted(v, side='left')

            # result returns 0 if v is first element or if v is not in metadata
            # check that metadata contains v
            if not result and v not in metadata:
                result = -1
            return TermValue(result, result, 'integer')
        elif kind == 'integer':
            v = int(float(v))
            return TermValue(v, v, kind)
        elif kind == 'float':
            v = float(v)
            return TermValue(v, v, kind)
        elif kind == 'bool':
            if isinstance(v, str):
                v = not v.strip().lower() in ['false', 'f', 'no',
                                              'n', 'none', '0',
                                              '[]', '{}', '']
            else:
                v = bool(v)
            return TermValue(v, v, kind)
        elif isinstance(v, str):
            # string quoting
            return TermValue(v, stringify(v), 'string')
        else:
            raise TypeError("Cannot compare {v} of type {typ} to {kind} column"
                            .format(v=v, typ=type(v), kind=kind))
704236
def to_python(self, value):
        
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day)
        if isinstance(value, list):
            # Input comes from a 2 SplitDateTimeWidgets, for example. So,
            # it's four components: start date and time, and end date and time.
            if len(value) != 4:
                raise ValidationError(self.error_messages['invalid'])
            if value[0] in validators.EMPTY_VALUES and value[1] in \
                    validators.EMPTY_VALUES and value[2] in \
                    validators.EMPTY_VALUES and value[3] in \
                    validators.EMPTY_VALUES:
                return None
            start_value = '%s %s' % tuple(value[:2])
            end_value = '%s %s' % tuple(value[2:])

        start_datetime = None
        end_datetime = None
        for format in self.input_formats or formats.get_format(\
                'DATETIME_INPUT_FORMATS'):
            try:
                start_datetime = datetime.datetime(*time.strptime(\
                        start_value, format)[:6])
            except ValueError:
                continue

        for format in self.input_formats or formats.get_format(\
                'DATETIME_INPUT_FORMATS'):
            try:
                end_datetime = datetime.datetime(*time.strptime(\
                        end_value, format)[:6])
            except ValueError:
                continue

        return (start_datetime, end_datetime)