AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' in Python
Hi guys, I have a short code with Python. I want to manipulate with datetime
package. I have an array that will store date data and use for
loop to add date value to that array. You can see it here:
from datetime import datetime, timedelta
today = datetime.now()
dates = []
dates.append(today.strftime("%d%m%Y"))
for i in range(0, 10):
next_day = today + datetime.timedelta(days=i)
dates.append(next_day.strftime("%d%m%Y"))
print(dates)
But run this code I got an exception AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'. Below is the detail of that exception:
Traceback (most recent call last):
File "main.py", line 6, in <module>
next_day = today + datetime.timedelta(days=i)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
** Process exited - Return Code: 1 **
Press Enter to exit terminal
I install Python version 3.10 and coding on window 11.
Thanks in advance.
-
S0
Simeon Ezechinyere Jul 04 2022
The error occurs because we imported the
datetime
class. When we try to calltimedelta
we are trying to calldatetime.datetime.timedelta
which does not exist.Solution 1
Remove the extra
datetime
, as we have imported thetimedelta
class. See an example here:from datetime import datetime, timedelta today = datetime.now() dates = [] dates.append(today.strftime("%d%m%Y")) for i in range(0, 10): next_day = today + timedelta(days=i) # REMOVE datetime here dates.append(next_day.strftime("%d%m%Y")) print(dates)
#Output
['04072022', '04072022', '05072022', '06072022', '07072022', '08072022', '09072022', '10072022', '11072022']
Solution 2
Use import
datetime
only, import thedatetime
module and then access thetimedelta
constructor throughdatetime.timedelta()
. Like this:import datetime dates = [] today = datetime.datetime.now() dates.append(today.strftime("%d%m%Y")) for i in range(0, 10): next_day = today + datetime.timedelta(days=i) dates.append(next_day.strftime("%d%m%Y")) print(dates)
And the result is the same as solution 1.
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.