发布网友 发布时间:2022-04-23 15:08
共2个回答
懂视网 时间:2022-04-19 03:11
本文实例讲述了python根据出生日期获得年龄的方法。分享给大家供大家参考。具体如下:这段代码可以根据用户的出生日期获得其年龄,born参数为date类型
def calculate_age(born): today = date.today() try: birthday = born.replace(year=today.year) except ValueError: # raised when birth date is February 29 # and the current year is not a leap year birthday = born.replace(year=today.year, day=born.day-1) if birthday > today: return today.year - born.year - 1 else: return today.year - born.year
希望本文所述对大家的Python程序设计有所帮助。
热心网友 时间:2022-04-19 00:19
摘要python根据出生日期计算年龄的代码,运行后会提醒用户输出出生的年月日,然后输出年龄,可以改写为一个通用函数from time import *#a function to find your agedef age():print "Enter Your Date of Birth"d=input("Day:")m=input("Month:")y=input("Year:")#get the current time in tuple formata=gmtime()#difference in daydd=a[2]-d#difference in monthdm=a[1]-m#difference in yeardy=a[0]-y#checks if difference in day is negativeif dd<0:dd=dd+30dm=dm-1#checks if difference in month is negative when difference in day is also negativeif dm<0:dm=dm+12dy=dy-1#checks if difference in month is negative when difference in day is positiveif dm<0:dm=dm+12dy=dy-1print "Your current age is %s Years %s Months & %s Days"%(dy,dm,dd)age()咨询记录 · 回答于2021-11-22用python做(统计老人年龄(60岁以上)从键盘输入,人员的年龄存放在列表、统计出的各年龄(每10岁为一个年龄段)的人数存在字典中python根据出生日期计算年龄的代码,运行后会提醒用户输出出生的年月日,然后输出年龄,可以改写为一个通用函数from time import *#a function to find your agedef age():print "Enter Your Date of Birth"d=input("Day:")m=input("Month:")y=input("Year:")#get the current time in tuple formata=gmtime()#difference in daydd=a[2]-d#difference in monthdm=a[1]-m#difference in yeardy=a[0]-y#checks if difference in day is negativeif dd<0:dd=dd+30dm=dm-1#checks if difference in month is negative when difference in day is also negativeif dm<0:dm=dm+12dy=dy-1#checks if difference in month is negative when difference in day is positiveif dm<0:dm=dm+12dy=dy-1print "Your current age is %s Years %s Months & %s Days"%(dy,dm,dd)age()以上答案仅供参考,实际情况要根据您的运行系统进行了修改哟~希望我的回答对您能有所帮助哟~