Jessica Chambers
Jessica Chambers

Reputation: 1316

Unsupported operand type(s) for /: 'datetime.timedelta' and 'datedelta'

I'm trying to calculate a time period length, but as one date is a timedelta and the other is a datedelta, this error is thrown:

Unsupported operand type(s) for /: 'datetime.timedelta' and 'datedelta'

Code:

from datetime import timedelta
from datedelta import datedelta
import math

step_period = datedelta(months=1)
to_from = timedelta(weeks=6)
number_of_steps = math.ceil((to_from) / step_period)

NB: datedelta is a Python library: it can be obtained wih sudo pip3 install datedelta

Possible input:

My length of time to consider is 6 weeks (to_from), I wish to divide it into chunks (number_of_steps) of 1 month (step_period). How many divisions will there be?

Expected output: number_of_steps = 2

How can I solve this?

Upvotes: 1

Views: 951

Answers (2)

quamrana
quamrana

Reputation: 39354

You need to convert to the same units and then do a division: (having installed datedelta package)

from datetime import timedelta
from datedelta import datedelta
import math

def delta_to_days(delta):
    return delta.days + delta.months * 30

step_period = datedelta(months=1)
to_from = timedelta(days=3)
number_of_steps = math.ceil(delta_to_days(step_period) / to_from.days )
print(number_of_steps)

Output:

10

Upvotes: 2

Cr1064
Cr1064

Reputation: 439

I'm pretty sure timedelta won't allow for months= as an input. I also could not find this datedelta you have. Instead I could replicate your answer as per:

In: math.ceil(timedelta(weeks=6)/timedelta(weeks=4))
Out: 2

Upvotes: 1

Related Questions