如何用python计算年龄_使用python计算年龄(以天为单位)

作为课程的一部分,我必须用天来定义年龄。

前3部分工作正常,但最后一部分不工作。在这里,我必须在前面的函数中导入两个日期(age_in_days)和date of today。有人能解释一下这是怎么回事吗import datetime

def days_in_month(year, month):

"""

Inputs:

year - an integer between datetime.MINYEAR and datetime.MAXYEAR

representing the year

month - an integer between 1 and 12 representing the month

Returns:

The number of days in the input month.

"""

if month==12:

return 31

else:

date1 = datetime.date(year, month, 1)

date2 = datetime.date(year, month+1, 1)

difference = date2 - date1

return(difference.days)

#print(days_in_month(2012,2))

def is_valid_date(year, month, day):

"""

Inputs:

year - an integer representing the year

month - an integer representing the month

day - an integer representing the day

Returns:

True if year-month-day is a valid date and

False otherwise

"""

if datetime.MINYEAR<=year<=datetime.MAXYEAR and 1<=month<=12 and 1<=day<= days_in_month(year, month):

return True

else:

return False

#print(is_valid_date(2012,10,21))

def days_between(year1, month1, day1, year2, month2, day2):

"""

Inputs:

year1 - an integer representing the year of the first date

month1 - an integer representing the month of the first date

day1 - an integer representing the day of the first date

year2 - an integer representing the year of the second date

month2 - an integer representing the month of the second date

day2 - an integer representing the day of the second date

Returns:

The number of days from the first date to the second date.

Returns 0 if either date is invalid or the second date is

before the first date.

"""

date1=datetime.date(year1,month1,day1)

date2=datetime.date(year2,month2,day2)

if is_valid_date(year1,month1,day1) and is_valid_date(year2,month2,day2)and (date1

difference=date2-date1

#print(difference.days)

return difference.days

else:

return 0

def age_in_days(year, month, day):

"""

Inputs:

year - an integer representing the birthday year

month - an integer representing the birthday month

day - an integer representing the birthday day

Returns:

The age of a person with the input birthday as of today.

Returns 0 if the input date is invalid or if the input

date is in the future.

"""

todays_date=datetime.date.today()

if is_valid_date(year, month,day) and (age_in_days

return days_between(age_in_days(year,month,day),todays_date(year,month,day))

else:

return 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值