Why is Python datetime time delta not found?

不羁的心 提交于 2019-11-27 23:39:51

问题


I am trying to make an array of dates in mmddyyyy format. The dates will start on the current day and then go two weeks into the future. So it all depends on the starting date. When I run my code I get an error that states:

Traceback (most recent call last):
File "timeTest.py", line 8, in <module>
day = datetime.timedelta(days=i)
AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'

I am not sure why this is happening because after searching online, I noticed that people are using the 'timedelta' in this way.

Here is my code:

import time
from datetime import datetime, date, time, timedelta

dayDates = []
today = datetime.now()
dayDates.append(today.strftime("%m%d%Y"))
for i in range(0,14):
    day = today + datetime.timedelta(days=i)
    print day

回答1:


import time
from datetime import datetime, date, time, timedelta

dayDates = []
today = datetime.now()
dayDates.append(today.strftime("%m%d%Y"))
for i in range(0,14):
    day = today + datetime.timedelta(days=i)
    print day

The error that you are getting says, that datetime has no attribute timedelta. It happens, because you have imported from datetime specific things. In order to access timedelta now you type timedelta instead of datetime.timedelta.

import time
from datetime import datetime, date, time, timedelta

dayDates = []
today = datetime.now()
dayDates.append(today.strftime("%m%d%Y"))
for i in range(0,14):
    day = today + timedelta(days=i)
    print day

Like that, your code should work properly. Also, pay closer attention to the error messages and try to read them carefully. If you focus enough, you often can sort out the problem basing on them on your own.




回答2:


You already imported timedelta. You don't need to access it through datetime.

import time
from datetime import datetime, date, time, timedelta

dayDates = []
today = datetime.now()
dayDates.append(today.strftime("%m%d%Y"))
for i in range(0,14):
    day = today + timedelta(days=i)
    print day



回答3:


The method you want to call is datetime.timedelta, as seen here. datetime is the module containing timedelta.

If you look at your import line:

from datetime import datetime, date, time, timedelta

...you'll see you're importing the datetime class from the datetime module. So, when you call datetime.timedelta, you're actually calling datetime.datetime.timedelta, which doesn't exist.



来源:https://stackoverflow.com/questions/37980655/why-is-python-datetime-time-delta-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!