Search code examples
pythondatetimetypeerrortimedelta

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


Solution

  • 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 --------------^