Message 75877 - Python tracker (original) (raw)
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(13600 + 2460 + 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