Home > Net >  How do I fix AttributeError: type object 'datetime.datetime' has no attribute 'timede
How do I fix AttributeError: type object 'datetime.datetime' has no attribute 'timede

Time:08-09

I've been working on some code to track stocks and have been using the datetime function to get x number or days ago, decided by user input. However, I have been getting the error

line 12, in amount_Of_Days_Ago = today - datetime.datetime.timedelta(days=amount_Of_Days_Ago) AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

Here's my code

import datetime

print('How many days ago should the smaller period of time be?')

amount_Of_Days_Ago = input()

amount_Of_Days_Ago = int(amount_Of_Days_Ago)

today = datetime.datetime.now()

amount_Of_Days_Ago = today - datetime.datetime.timedelta(days=amount_Of_Days_Ago)

amount_Of_Days_Ago = amount_Of_Days_Ago.strftime('%Y-%m-%d')
today = today.strftime('%Y-%m-%d')

amount_Of_Days_Ago = str(amount_Of_Days_Ago)
today = str(today)

response = requests.get("http://api.marketstack.com/v1/eod?access_key=###########&symbols=AAPL&date_from="   amount_Of_Days_Ago   "&date_to="   today)

print(response) 

CodePudding user response:

Indeed, there is only the need to call datetime once after importing it. Have a look at the docs here. Consider using:

amount_Of_Days_Ago = today - datetime.timedelta(days=amount_Of_Days_Ago)

Or:

from datetime import timedelta
amount_Of_Days_Ago = today - timedelta(days=amount_Of_Days_Ago)

CodePudding user response:

You have to import the timedelta function from the datetime library. As in:

     import datetime
     from datetime import timedelta
  • Related