Question

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?

Was it helpful?

Solution

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
0.5
>>> td2 = timedelta(days=4, minutes=50)
>>> td1.total_seconds() / td2.total_seconds()
0.24784853700516352
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top