def ensure_timedelta(delta):
    """
    Attempts to convert an object to a time delta.

    @rtype
      `datetime.timedelta`
    """
    if isinstance(delta, datetime.timedelta):
        return delta

    if isinstance(delta, str):
        # FIXME
        match = re.match(r"(\d+) *(d|h|m|s)", delta)
        if match is not None:
            num, unit = match.groups()
            if unit == "d":
                return datetime.timedelta(int(num), 0)
            else:
                secs = int(num) * {"h": 3600, "m": 60, "s": 1}.get(unit)
                return datetime.timedelta(0, secs)

    raise TypeError("not a timedelta: {!r}".format(delta))
dataset/ETHPy150Open twosigma/ngrid/ngrid/datetime.py/ensure_timedelta/original