Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

timedelta - Why is Python datetime time delta not found?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...