Calculate days until your next birthday in python
A couple of problems:
- Year must be specified as a complete integer, i.e. 2002, not 02 (or 2).
- You need to check whether or not your birthdate has passed for this year.
Below is a solution which corrects these 2 issues. Given your input 20-Feb-2002 and today's date 31-Jul-2018, your next birthday is in 203 days' time.
In addition, note you can use the days
attribute of a timedelta
object, which will round down to 203 days and avoid the decimal precision.
from datetime import datetime
def get_user_birthday():
year = int(input('When is your birthday? [YY] '))
month = int(input('When is your birthday? [MM] '))
day = int(input('When is your birthday? [DD] '))
birthday = datetime(2000+year,month,day)
return birthday
def calculate_dates(original_date, now):
delta1 = datetime(now.year, original_date.month, original_date.day)
delta2 = datetime(now.year+1, original_date.month, original_date.day)
return ((delta1 if delta1 > now else delta2) - now).days
bd = get_user_birthday()
now = datetime.now()
c = calculate_dates(bd, now)
print(c)
When is your birthday? [YY] 02
When is your birthday? [MM] 02
When is your birthday? [DD] 20
113
Think about what your calculate_dates
function is doing.
You are getting your birthday, and then looking at how far the current time is from that birthday in the current year. Hence, what you are doing is finding the number of days to your birthday in the current year, whether or not it has past.
For example, take your birthday February 20th. Your date2
will be 2018-2-20
rather than 2019-2-20
.
You can fix this by checking whether or not the day has already passed in this year.