Pren Ven
Pren Ven

Reputation: 177

Type Error with operations with dates (datetime package)

I have this code:

 import datetime

 last_date = datetime.datetime(2021, 1, 15)
 first_date = datetime.datetime(2021, 1, 1)

 date_1 = last_date - first_date

 print(date_1) #this prints: 14 days, 00:00:00

 r=0.05

 fa = 1/(1+r)**(date_1/360)

 fa

I get this error:

TypeError: unsupported operand type(s) for ** or pow(): 'float' and 'datetime.timedelta'

I'm interested in the number of the days, not with the hours

Upvotes: 3

Views: 55

Answers (2)

Mureinik
Mureinik

Reputation: 311143

date_1 is a timedelta object, and as you've seen you can't divide it by a float. ]You can extract the number of days from it by using the days property:

fa = 1/(1+r)**(date_1.days/360)
# Here --------------^

Upvotes: 1

Marcelo Wizenberg
Marcelo Wizenberg

Reputation: 121

date_1 is a datetime.timedelta object. You need to get the number of days as an integer.

import datetime

 last_date = datetime.datetime(2021, 1, 15)
 first_date = datetime.datetime(2021, 1, 1)

 date_1 = last_date - first_date

 print(date_1) #this prints: 14 days, 00:00:00

 r=0.05

 fa = 1/(1+r)**(date_1.days/360)

 fa

Upvotes: 0

Related Questions