Take the 2-minute tour ×

I am working on an advanced timekeeping and time statistics application. I'm using Python timedelta objects to represent spans of time within the app.

What I'm trying to figure out is if there's a way to represent an arbitrary fraction of a timedelta object.

The provided operators for timedelta only allow working with integers. You can multiply a timedelta by an integer, and you can divide it by an integer, but you can't do either with floats.

I want to be able to do two things:

1: Given a timedelta object, figure out an arbitrary percentage of it. In other words, the ability to multiply or divide by floats:

from datetime import timedelta
import math
td = timedelta(1)
newTd = td * 0.01 # 1% of the time delta specified in td
newTd = td * 1.04 # 104% of the time delta given in td
newTd = td * math.pi # the timedelta multiplied by pi (lol) 

2: Given two timedelta objects, figure out the percentage of time span given by one timedelta with respect to another time delta as a float:

from datetime import timedelta
td1 = timedelta(1)
td2 = timedelta(2)
td1 / td2 # should give me 0.5
td2 = timedelta(days=4, minutes=50)
td1 / td2 # not sure what this would result in, but, the percentage of time 1 day fills out of 4 days and 50 minutes of time

Both of these require me to be able to operate on timedelta objects using floats. I'm not sure if this can be done. So, Can it be done, and if not, is there a better alternative to this?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

You can get the number of seconds from a timedelta with .total_seconds() and use that.

>>> from datetime import timedelta
>>> td1 = timedelta(1)
>>> td2 = timedelta(2)
>>> td1.total_seconds() / td2.total_seconds() # should give me 0.5
>>> td2 = timedelta(days=4, minutes=50)
share|improve this answer
excellent! thanks! –  fdmillion May 26 '13 at 9:37
In python3 you can operate directly on timedelta objects using floats or divide two timedelta objects obtaining a float. –  Zac May 26 '13 at 10:12
add comment

Your Answer


