Convertd timedelta to Duration.
961600
def FromTimedelta(self, td):
    """"""
    self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY,
                            td.microseconds * _NANOS_PER_MICROSECOND)
905401
def parse_timedelta(ev):
    

    chunks = ev['event-duration'].split()
    tdargs = {}
    for c in chunks:
        try:
            m = TIME_MULTIPLIERS[c[-1]]
            val = int(c[:-1])
            tdargs[m] = val
        except KeyError:
            log.error("""Unknown time multiplier '%s' value in the \
'event-duration' field in the '%s' event. Supported multipliers \
are: '%s'.""" % (c, ev['title'], ' '.join(TIME_MULTIPLIERS)))
            raise RuntimeError("Unknown time multiplier '%s'" % c)
        except ValueError:
            log.error("""Unable to parse '%s' value in the 'event-duration' \
field in the '%s' event.""" % (c, ev['title']))
            raise ValueError("Unable to parse '%s'" % c)


    return timedelta(**tdargs)
805693
def format_timedelta(dt: timedelta) -> str:
    
    seconds = int(dt.total_seconds())
    days, remainder = divmod(seconds, 86400)
    hours, remainder = divmod(remainder, 3600)
    minutes, seconds = divmod(remainder, 60)
    s = ""
    if days > 0:
        s += str(days) + "d"
    if hours > 0:
        s += str(hours) + "h"
    if minutes > 0:
        s += str(minutes) + "min"
    if s == "":
        s = "0min"
    return s
51503
def round_to_5_minutes(moment):
    '''
    '''
    return moment - timedelta(minutes=moment.minute % 5, seconds=moment.second)
634083
def _print_duration(self):
        ''''''
        duration = int(time.time() - self._start_time)
        self._print(datetime.timedelta(seconds=duration))
1161780
def duration(self):
        
        if self.time_end is None or self.time_start is None:
            return timedelta(seconds=0)
        else:
            return self.time_end - self.time_start
148711
def timedelta_to_duration(dt):
    
    days, secs = dt.days, dt.seconds
    res = 'P'
    if days // 7:
        res += str(days // 7) + 'W'
        days %= 7
    if days:
        res += str(days) + 'D'
    if secs:
        res += 'T'
        if secs // 3600:
            res += str(secs // 3600) + 'H'
            secs %= 3600
        if secs // 60:
            res += str(secs // 60) + 'M'
            secs %= 60
        if secs:
            res += str(secs) + 'S'
    return res
460188
def _subtract_timedelta(self, delta):
        
        if isinstance(delta, pendulum.Duration):
            return self.subtract(
                years=delta.years,
                months=delta.months,
                weeks=delta.weeks,
                days=delta.remaining_days,
                hours=delta.hours,
                minutes=delta.minutes,
                seconds=delta.remaining_seconds,
                microseconds=delta.microseconds,
            )

        return self.subtract(
            days=delta.days, seconds=delta.seconds, microseconds=delta.microseconds
        )
1069963
def _seconds_or_timedelta(duration):
    
    if isinstance(duration, int):
        dt_timedelta = timedelta(seconds=duration)
    elif isinstance(duration, timedelta):
        dt_timedelta = duration
    else:
        raise TypeError(
            'Expects argument as `datetime.timedelta` object '
            'or seconds in `int` format'
        )

    return dt_timedelta
1182218
def as_timedelta(cls, delta):
        """"""
        # Cannot monkey patch the __class__ and must pass through __new__ as the object is immutable.
        if isinstance(delta, cls): return delta
        return cls(delta.days, delta.seconds, delta.microseconds)
430375
def _to_seconds(timestr):
    '''
    
    '''
    timestr = timestr.upper()
    if 'H' in timestr:
        seconds = int(timestr.replace('H', '')) * 3600
    elif 'D' in timestr:
        seconds = int(timestr.replace('D', '')) * 86400
    elif 'W' in timestr:
        seconds = 604800
    else:
        try:
            seconds = int(timestr)
        except ValueError:
            seconds = 604800
    if seconds > 604800:
        seconds = 604800
    return seconds
778602
def timedelta_seconds(value: datetime.timedelta) -> int:
    
    return SECONDS_PER_DAY * value.days + value.seconds
1668
def parse_duration_with_start(start, duration):
    
    elements = _parse_duration_string(_clean(duration))
    year, month = _year_month_delta_from_elements(elements)

    end = start.replace(
        year=start.year + year,
        month=start.month + month
    )

    del elements['years']
    del elements['months']

    end += _timedelta_from_elements(elements)

    return start, end - start
1344236
def from_str(duration):
    """"""

    if duration in ("0", "+0", "-0"):
        return datetime.timedelta()

    pattern = re.compile('([\d\.]+)([a-zµμ]+)')
    total = 0
    sign = -1 if duration[0] == '-' else 1
    matches = pattern.findall(duration)

    if not len(matches):
        raise Exception("Invalid duration {}".format(duration))

    for (value, unit) in matches:
        if unit not in units:
            raise Exception(
                "Unknown unit {} in duration {}".format(unit, duration))
        try:
            total += float(value) * units[unit]
        except:
            raise Exception(
                "Invalid value {} in duration {}".format(value, duration))

    microseconds = total / _microsecond_size
    return datetime.timedelta(microseconds=sign * microseconds)
713388
def get_timedelta(self, now=None):
        
        def datetime_to_time(timestamp):
            atime = time.mktime(timestamp.timetuple())
            atime += timestamp.microsecond / 10.0**6
            return atime
        if self.started is not None:
            now = now or datetime.datetime.now()
            started_time = datetime_to_time(self.started)
            now_time = datetime_to_time(now)
            return now_time - started_time
        return None
1081209
def convert_duration(duration):
    '''
    
    '''

    # durations must be specified in days, weeks or hours

    if duration.endswith('h'):
        hours = int(duration.split('h'))

    elif duration.endswith('d'):
        days = duration.split('d')
        hours = int(days[0]) * 24

    elif duration.endswith('w'):
        weeks = duration.split('w')
        hours = int(weeks[0]) * 24 * 7

    duration_string = str(hours)+'h0m0s'
    return duration_string
1264208
def duration_minutes(duration):
    """"""
    if isinstance(duration, list):
        res = dt.timedelta()
        for entry in duration:
            res += entry

        return duration_minutes(res)
    elif isinstance(duration, dt.timedelta):
        return duration.total_seconds() / 60
    else:
        return duration