Python中的字符串转换日期时间失败

时间:2015-12-24 21:01:57

标签: python datetime

我在python 2.7中编写了一个CPython程序来查找用户生日和当前日期之间的天数。

当我尝试使用 date 方法时,我能够实现此功能,但在尝试使用 datetime 方法时失败。当我使用datetime方法时,当前日期随时间推移而如果尝试减去用户出生日期则会出错。

所以我试图获取datetime输出的子字符串(例如:x = currentDate.strftime('%m /%d /%Y'))将其传递给变量然后转换为日期(例如:currentDate2 = datetime.strftime(' x',date_format))但它失败了。

你能帮我理解为什么吗

 from  datetime import datetime
    from datetime import date
    currentDate3 = ''
    currentDate = datetime.today()
    currentDate1 = date.today()
    currentDate3 = currentDate.strftime('%m/%d/%Y')
    date_format = "%m/%d/%Y"
    currentDate2 = datetime.strftime('currentDate3', date_format)
     # The above line is giving error "descriptor 'strftime' requires a 'datetime.date' object but received a 'str'"
    print(currentDate3)
    print(currentDate1)
    print(currentDate.minute)
    print(currentDate)

    userInput = raw_input('Please enter your birthday (mm/dd/yyyy)')
    birthday = datetime.strptime(userInput, '%m/%d/%Y').date()
    print(birthday)

    days = currentDate1 - birthday
    days = currentDate2 - birthday
    print(days.days)

1 个答案:

答案 0 :(得分:1)

您正在尝试格式化字符串而不是日期时间:

currentDate2 = datetime.strftime('currentDate3', date_format)

但是,您不需要将当前日期格式化为此任务的字符串 - 您需要datetime才能计算它与用户输入的日期字符串之间的天数,您要将.strptime()加载到datetime

工作样本:

from datetime import datetime

currentDate = datetime.now()

userInput = raw_input('Please enter your birthday (mm/dd/yyyy)')
birthday = datetime.strptime(userInput, '%m/%d/%Y')

days = (currentDate - birthday).days
print(days)