Beispiel #1
0
def coerce_type(value, datatype):
    if isinstance(value, datatype) or value is None:
        return value

    elif datatype == str:
        return str(value)

    elif datatype in (int, float):
        try:
            return datatype(value)
        except (TypeError, ValueError):
            pass

        if isinstance(value, str):
            numbers = tuple(extract_numbers(value))

            if len(numbers) > 1:
                raise ValueError("more than one number found")
            elif len(numbers) == 1:
                return datatype(numbers[0])

        elif isinstance(value, datetime.timedelta):
            return datatype(value.total_seconds() / 3600)

    elif datatype == datetime.timedelta:
        if isinstance(value, (int, float)):
            return datetime.timedelta(hours=24 * value)

        elif isinstance(value, datetime.time):
            return datetime.timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)

        elif isinstance(value, datetime.datetime):
            return value - EXCEL_START_DATE
Beispiel #2
0
 def test_extract_number(self):
     self.assertEqual(list(extract_numbers('2 people')), [2])
     self.assertEqual(list(extract_numbers('1, 2.2, 3., -.4')),
                      [1, 2.2, 3, -0.4])
     self.assertEqual(list(extract_numbers('no numbers')), [])