Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

python - datetime module: calculate someone's age in days, but the birthday date is out of range

Assume the person can live for thousands of years, and we calculate his age in days (the output has to be the number in days). My code is below

def age_in_days(year, month, day):

    today = datetime.date.today()
    birthday = datetime.date(year, month, day)

    age_day = today - birthday 
    return age_day.days

However, in the assignment dropbox, the system has input the year as 0, i.e. age_in_days(0, 5, 1).

My code consequently gave a ValueError, because in the Python datetime module, the range of year is from 1 to 9999, and 0 is out of the range. Hence, my programme failed to pass the test

Since the input year == 0 is a predefined test case, and I am expected to output an exact correct value (assignment is marked by machine) despite of the out-of-range input, instead of a try-except statement which returns something like "this year value is invalid, please enter a new one"

Is there a way to fix it?

question from:https://stackoverflow.com/questions/65640721/datetime-module-calculate-someones-age-in-days-but-the-birthday-date-is-out-o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...