0

I am practicing by creating an age calculator which calculates age in years based on given date of birth.

However it doesn't work the way I intend it to function. I want to show age in year e.g 19 to the user when their age is 19 and month is less than 6 and if the month is more than 6 then I want to add 1 to the age in this case 19+1.

Can anyone create the same program with the same concept in a better way? Please add some explanation so that it is easy for me to understand.

I am python beginner, so please excuse my bad code as well as my bad English. Thanks in advance for the help.

from datetime import date

Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
born = date(year = int(Doby) , month= int(Dobm) , day= int(Dobd))
today = date.today()
age = today.year - born.year
condition = today.month - born.month
if condition >= 6 :
    age += 1
elif condition <= -6 :
    age -= 1
print(age)
petezurich
  • 9,280
  • 9
  • 43
  • 57
Zakria Khan
  • 1,897
  • 1
  • 17
  • 22
  • Considering your requirements, this code works fine. Of course, your condition on `month` seems a bit off, because usually one would do `age -= 1` if `today.month < born.month` (since haven't reached the birthday yet). If it is past the birth month, the age is accurate. But if you are certain you need that 6 month difference check, with the associated +1 and -1, then your code works fine. – shriakhilc Jun 01 '19 at 05:02
  • If you have no errors in your code, but want a review of how it can be written better, you can try asking on https://codereview.stackexchange.com/ – shriakhilc Jun 01 '19 at 05:03

6 Answers6

0

Suppose today is 01/01/2019 and input is 12/06/1989. The output we need is 29years and 7 months.

   if  condition >= 0:
    Totmonth = condition 
  else:
     Totmonth = 12+condition 
      age -= 1

  print "age is" , age,"years and", Totmonth,"months"
Nija I Pillai
  • 1,046
  • 11
  • 13
0

I subtracted the int(age) from 'age' to get the decimal port of the age.

days_in_year = 365.2425    
age = (date.today() - born).days / days_in_year
decAge = age - int(age)

Then checked to see if the decimal portion is greater than 0.5 and set 'age' accordingly.

if decAge > 0.5 :
  age = int(age) + 1
else:
  age = int(age)

I think that works.

BlackBear
  • 81
  • 1
  • 4
0

You can just divide with no of days in a year and do rounding (round half up) to get the desired result. The below code should work.

from datetime import date

# Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
Doby, Dobm, Dobd = 1999, 11, 1
born = date(year=int(Doby), month=int(Dobm), day=int(Dobd))
today = date.today()

print(round((today-born).days/365.25))

Output:

20
Praveenkumar
  • 2,056
  • 1
  • 9
  • 18
0

here is your function

def years_of_age():
    from datetime import date, datetime
    dob = input("Please enter your DOB as mm-dd-yyyy: ")

    #time delta in days
    val = date.today().toordinal() - datetime.strptime(dob, "%m-%d-%Y").toordinal()

    # this is just so you can confirm, comment out the following 4 lines
    print("months {}, years {}".format(\
                                       int(datetime.fromordinal(val).strftime("%m")),\
                                       int(datetime.fromordinal(val).strftime("%Y"))\
                                      ))

    # conditional return based on the months figure
    if int(datetime.fromordinal(val).strftime("%m")) >=6:
        return int(datetime.fromordinal(val).strftime("%Y")) + 1
    else:
        return int(datetime.fromordinal(val).strftime("%Y"))

Here are a few examples

years_of_age()

Please enter your DOB as mm-dd-yyyy: 5-16-1976
months 1, years 44
44

years_of_age()

Please enter your DOB as mm-dd-yyyy: 7-16-1976
months 11, years 43
44

years_of_age()

Please enter your DOB as mm-dd-yyyy: 2-16-1977
months 4, years 43
43

  • instance method .toordinal() converts a datetime object into a number of days since Jan 1 0000.
  • the instance method .strftime() converts a string to a datetime object given that there are format directives datetime ("%m-%d-%Y").

  • since you are a beginner I made sure to use python standard library packages, not because numpy is too advanced, because standard library packages are efficient, great and overlooked.

hussam
  • 830
  • 9
  • 17
0

In my case I need age,month and day from birthday ,my function below,

import datetime
from datetime import date

def Calc(): 
born_date = "02-08-1999"
born = datetime.strptime(born_date, '%d-%m-%Y')
today = date.today()
curr_month = today.month
born_month = born.month

curr_day   = today.day
born_day   = born.day

if born_month > curr_month:
    month_diff = born_month - curr_month
else :
    month_diff = curr_month - born_month
    

if born_day > curr_day:
    day_diff = born_day - curr_day
else :
    day_diff = curr_day - born_day

    
age = today.year - born.year
print(str(age))
print(month_diff)
print(str(day_diff))
return " Your Age  : " + str(age) +"  Years   " + str(month_diff) +  "  Months  and " + str(day_diff) + "  Days"
Ganesan J
  • 539
  • 7
  • 12
0
import datetime

def age(dob, on_date=None):
    # By default, use the current date for on_date
    if on_date is None:
        on_date = datetime.date.today()
    # Subtracting the years gives age at *end* of year
    age = on_date.year - dob.year
    # Adjust if they haven't had their birthday yet.
    if (on_date.month, on_date.day) < (dob.month, dob.day):
        age -= 1
    return age

The last if statement takes advantage of how Python compares tuples so that if the months are the same, the comparison will be based on the day of the month.

>>> # Calculate my own age
>>> age(datetime.date(1982, 12, 21))
39
>>> # My age increases on my birthday.
>>> age(datetime.date(1982, 12, 21), datetime.date(2022, 12, 21))
40
dan04
  • 87,747
  • 23
  • 163
  • 198