Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate days until your next birthday in python

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)
like image 621
Taha Jalili TATI Avatar asked Jul 31 '18 18:07

Taha Jalili TATI


2 Answers

A couple of problems:

  1. Year must be specified as a complete integer, i.e. 2002, not 02 (or 2).
  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
like image 181
jpp Avatar answered Sep 30 '22 00:09

jpp


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.

like image 33
Ziyad Edher Avatar answered Sep 30 '22 00:09

Ziyad Edher