AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' in Python

Dung Do Tien Jul 04 2022 194

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.

Have 1 answer(s) found.
  • S

    Simeon Ezechinyere Jul 04 2022

    The error occurs because we imported the datetime class. When we try to call timedelta we are trying to call datetime.datetime.timedelta which does not exist.

    Solution 1

    Remove the extra datetime, as we have imported the timedelta 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 the datetime module and then access the timedelta constructor through datetime.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.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close