In the code above I wanted to calculate days until next birthday but the output is wrong. what it should be: My birth day: Feb 20 2002 => 203 days until my birthday(today is july 31 2018) what it actually is: input: Feb 20 2002 => 179 days
My code:
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.datetime(year,month,day)
return birthday
def calculate_dates(original_date, now):
date1 = now
date2 = datetime.datetime(now.year, original_date.month, original_date.day)
delta = date2 - date1
days = delta.total_seconds() / 60 /60 /24
return days
def show_info(self):
pass
bd = get_user_birthday()
now = datetime.datetime.now()
c = calculate_dates(bd,now)
print(c)
A couple of problems:
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