[英]Datetime to string conversion failed in Python
我在python 2.7中编写了一个CPython程序,以查找用户生日与当前日期之间的天数。
当我尝试使用date方法时,我能够实现这一点,但是当我尝试使用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)
您正在尝试格式化字符串而不是日期时间:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.