这是我的代码&这是我的错误:AttributeError:type object' datetime.datetime'没有属性' strptime
#Trying to calculate how many days until a project is due for
import datetime
project = input('When is your project due for Please specify mm/dd/yyyy ')
deadline = datetime.datetime.strptime(project, '%m/%d/Y').date()
days = project - deadline
print(days)
print(days.days)
提前感谢#KOH
答案 0 :(得分:0)
看起来你需要这样的东西:
import datetime
project = input('When is your project due for. Please specify mm/dd/yyyy ')
deadline = datetime.datetime.strptime(project, '%m/%d/%Y').date()
delta = deadline - datetime.datetime.now().date()
print(delta.days)
使用Python3,datetime没有错误:
>>> datetime.datetime.strptime("08/11/2015", "%m/%d/%Y").date()
datetime.date(2015, 8, 11)
答案 1 :(得分:0)
我不确定你为什么会得到那个AttributeError
,但我想我们在评论中解决了这个问题。您也收到错误,因为您的格式字符串缺少%
。一旦你解决了这个问题,你就会收到一条错误消息,指出你无法从date
中减去str
。
即使修复了所有错误,代码所做的也不是你想要做的。看起来你试图从用户自己减去用户提供的日期,但我猜你想从用户提供的日期中减去今天的日期,以便获得用户提供日期之前的天数。
这是固定代码,其中包含一些格式和其他更改。
from datetime import datetime
deadline_str = input('When is your project due? Specify mm/dd/yyyy: ')
deadline = datetime.strptime(deadline_str, '%m/%d/%Y').date()
days_till_deadline = (deadline - datetime.today().date()).days
print("{0} days till the project is due.".format(days_till_deadline))
答案 2 :(得分:0)
所以这是我编写的代码,它有效......
#todays date programme
import datetime
currentDate = datetime.date.today()
#currentDate is date which is converted to string with variable current in the format dd/mm/yyyy
current = datetime.datetime.strftime(currentDate, '%d/%m/%Y')
#input statements
userInput = input('Please enter your project deadline (dd/mm/yyyy)\n')
print()
##prints...
print("Today's Date is "+current)
print()
print("Your project deadline is " + userInput)
#userInput is a string which is converted to date with variable Input
Input = datetime.datetime.strptime(userInput, "%d/%m/%Y").date()
##Calculating remaining days
remainingDays = Input - currentDate
remainingDays = remainingDays.days
print()
print('The days remaining for deadline are '+str(remainingDays)+' days')
答案 3 :(得分:-1)
我想是这样的。 因为在这里我们必须先导入日期时间,所以我们需要处理日期。 然后,我们必须获取当前日期,以便能够获得项目截止日期。
import datetime
current_date = datetime.datetime.now()
user = input('Enter the days left for your project: ')
deadline = datetime.datetime.strptime(user, '%d%m%Y').date()
days_left = deadline - current_date.date()
print(days_left.days)