hi,
I'm newbie in python and I'm using python 3.1
From the project ideas thread, I try to write a small module to calculate your age in years, months and days. Calculating the ages without the month (only years and days) would be easy, but adding the months makes me start to think about the algorithms.
Since I'm new, I don't know whether there are already methods from available modules in python.
The code is working correctly already (I tried to put in several possibilities and all result seems to be correct). But I don't feel satisfied with my code, as I think that the code can still be optimized.
Any ideas, advices, critiques are welcome.
def agecounter():
dd = int(input('Enter your Day of Birth: '))
mm = int(input('Enter your Month of Birth: '))
yy = int(input('Enter your Year of Birth: '))
from datetime import date
birthday = date(yy,mm,dd)
now = date.today()
now_dd = now.day
now_mm = now.month
now_yy = now.year
lastyear = date(now_yy,mm,dd) # Latest birthday year
if lastyear > now: # This year not yet having birthday
last_yy = now_yy - 1 # Last birtday is last year
lastyear = date(last_yy,mm,dd)
yearage = lastyear.year - birthday.year # Count year age
# Counting the month age
if now_mm >= mm:
if now_mm - mm > 1:
monthage = now_mm - mm
elif now_mm - mm == 1:
if now_dd > dd:
monthage = 1
else:
monthage = 0
else:
if yearage == 0 and now_mm == mm and now_dd < dd:
monthage = 11
else:
monthage = 0
else:
if now_dd > dd:
monthage = 12 + now_mm - mm
else:
monthage = 11 + now_mm - mm
lastmonth = date(now_yy,last_mm,dd)
# Counting the day age
if now_dd > dd:
last_mm = now_mm # Use this month as latest month
else:
last_mm = now_mm - 1 # Use last month as latest month
#dayage = now - lastyear
dayage = now - lastmonth
print('You were born on',birthday.strftime('%A'))
print('You are', yearage, 'years,',monthage,'months and',dayage.days, 'days old.')
#print('You are', yearage, 'years and',dayage.days, 'days old.')
agecounter()