We help IT Professionals succeed at work.

python calculating birthday

snhandle
snhandle asked
on
I am new to Python. try to learn. I want to create program where it should ask for birthday just day and month using input function and if the birthday is in the future then should give message that how many days left for your birthday, if it   is already passed then it should give message that your birthday was that many days ago and if it is today then should show message ‘happy birthday’
I spent lot of time but no luck
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2014

Commented:
What is the current state of your Python code?

Author

Commented:
import datetime
today_date = datetime.date.today()
birthday = input(“enter your birth date (DD/MM):”)
if x > 0
print(your birthday has already passed by” (x))
if x < 0
print(“u still have (x) days left”)
if x = 0
print(“happy birthday”)
Excel & VBA Expert
CERTIFIED EXPERT
Most Valuable Expert 2018
Awarded 2015
Commented:

You may try something like this...


import datetime

def is_valid_date(year, month, day):    
    try:
        dt = datetime.datetime(year, int(month), int(day))
        return True
    except ValueError:        
        return False


year = datetime.datetime.now().year
birth_month = input('Enter birth month: ')
birth_day = input('Enter birth day: ')
date_today = datetime.datetime.now()

if is_valid_date(year, birth_month,birth_day):
    birth_date = datetime.datetime(year, int(birth_month), int(birth_day))    
    num_days = (birth_date - date_today).days + 1
   
    if num_days == 0:
        print("Happy birthday!")
    elif num_days > 0:
        print(f'You still have {abs(num_days)} days.')
    else:
        print(f'Your birthday has already passed by {abs(num_days)} days.')
else:
    print('Invalid Date')

Author

Commented:
Always very helpful!! Thanks a lot
Subodh Tiwari (Neeraj)Excel & VBA Expert
CERTIFIED EXPERT
Most Valuable Expert 2018
Awarded 2015

Commented:

You're welcome!