[issue2706] datetime: define division timedelta/timedelta

STINNER Victor report at bugs.python.org
Fri Nov 14 18:51:30 CET 2008


STINNER Victor <victor.stinner at haypocalc.com> added the comment:

Why not also implementing divmod()? It's useful to split a timedelta 
into, for example, (hours, minutes, seconds):

def formatTimedelta(delta):
    """
    >>> formatTimedelta(timedelta(hours=1, minutes=24, seconds=19))
    '1h 24min 19sec'
    """
    hours, minutes = divmodTimedelta(delta, timedelta(hours=1))
    minutes, seconds = divmodTimedelta(minutes, timedelta(minutes=1))
    seconds, fraction = divmodTimedelta(seconds, timedelta(seconds=1))
    return "{0}h {1}min {2}sec".format(hours, minutes, seconds)

My implementation gives divmod(timedelta, timedelta) -> (long, 
timedelta). It's a little bit strange to get two different types in 
the result. The second return value is the remainder. My example works 
in the reverse order of the classical code:

def formatSeconds(seconds):
    """
    >>> formatTimedelta(1*3600 + 24*60 + 19)
    '1h 24min 19sec'
    """
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return "{0}h {1}min {2}sec".format(hours, minutes, seconds)
    
About my new patch:
 - based on datetime_datetime_division_dupcode.patch
 - create divmod() operation on (timedelta, timedelta)
 - add unit tests for the division (floor and true division) and 
divmod
 - update the documentation for the true division and divmod

----------
nosy: +haypo
Added file: http://bugs.python.org/file12011/timedelta_true_divide_divmod.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue2706>
_______________________________________


More information about the Python-bugs-list mailing list