Calculating age in python - python

I am attempting to create a code where the user is asked for their date of birth and today's date in order to determine their age. What I have written so far is:
print("Your date of birth (mm dd yyyy)")
Date_of_birth = input("--->")
print("Today's date: (mm dd yyyy)")
Todays_date = input("--->")
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(Date_of_birth)
However it is not running like I would hope. Could someone explain to me what I am doing wrong?

So close!
You need to convert the string into a datetime object before you can do calculations on it - see datetime.datetime.strptime().
For your date input, you need to do:
datetime.strptime(input_text, "%d %m %Y")
#!/usr/bin/env python3
from datetime import datetime, date
print("Your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print(age)
PS: I urge you to use a sensible order of input - dd mm yyyy or the ISO standard yyyy mm dd

This should work :)
from datetime import date
def ask_for_date(name):
data = raw_input('Enter ' + name + ' (yyyy mm dd): ').split(' ')
try:
return date(int(data[0]), int(data[1]), int(data[2]))
except Exception as e:
print(e)
print('Invalid input. Follow the given format')
ask_for_date(name)
def calculate_age():
born = ask_for_date('your date of birth')
today = date.today()
extra_year = 1 if ((today.month, today.day) < (born.month, born.day)) else 0
return today.year - born.year - extra_year
print(calculate_age())

You can also use date time library in this manner. This calculates the age in years and removes the logical error that returns wrong age due to the month and day properties
Like a person born on 31 July 1999 is a 17 year old till 30 July 2017
So here's the code :
import datetime
#asking the user to input their birthdate
birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")
birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()
print("Your birthday is on "+ birthDate.strftime("%d") + " of " + birthDate.strftime("%B, %Y"))
currentDate = datetime.datetime.today().date()
#some calculations here
age = currentDate.year - birthDate.year
monthVeri = currentDate.month - birthDate.month
dateVeri = currentDate.day - birthDate.day
#Type conversion here
age = int(age)
monthVeri = int(monthVeri)
dateVeri = int(dateVeri)
# some decisions
if monthVeri < 0 :
age = age-1
elif dateVeri < 0 and monthVeri == 0:
age = age-1
#lets print the age now
print("Your age is {0:d}".format(age))

from datetime import datetime, date
def calculateAge(birthDate):
today = date.today()
age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day))
return age
d=input()
year=d[0:4]
month=d[5:7]
day=d[8:]
if int(month)<=0 or int(month)>12:
print("WRONG")
elif int(day)<=0 or int(day)>31:
print("WRONG")
elif int(month)==2 and int(day)>29:
print("WRONG")
elif int(month) == 4 or int(month) == 6 or int(month) == 9 or int(month) ==11 and int(day) > 30:
print("WRONG")
else:
print(calculateAge(date(int(year),int(month),int(day))))
This code will work correctly for every date.

Related

Cognitive Complexity of functions should not be too high

When I use SonarLint to check code, it notifies Critical that Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.
I use a lot of if else statement, but can not use switch case.
This is my code:
str_time = str_time.lower()
if (bool(re.search(r'\d', str_time)) == True) and ('tối' or 'chiều' in str_time):
day = re.findall(r'\d+', str_time)[0]
if int(day) < datetime.date.today().day:
month = datetime.date.today().month + 1
else:
month = datetime.date.today().month
year = datetime.date.today().year
day = f'{year}-{month}-{day}'
return format_datetime(day)
elif 'hôm nay' in str_time or 'hn' in str_time or 'chiều nay' in str_time or 'tối nay' in str_time:
return format_datetime(datetime.date.today())
elif 'ngày mai' in str_time or 'mai' in str_time:
day = datetime.date.today() + datetime.timedelta(days=1)
elif 'ngày mốt' in str_time or 'mốt' in str_time:
day = datetime.date.today() + datetime.timedelta(days=2)
elif 'thứ 2 tuần sau' in str_time:
num = 7 - datetime.date.today().weekday() + 0
day = datetime.date.today() + datetime.timedelta(days=num)
elif 'thứ 3 tuần sau' in str_time:
num = 7 - datetime.date.today().weekday() + 1
day = datetime.date.today() + datetime.timedelta(days=num)
Sonar lint is right. It seems your code complexity is high. You should create smaller methods or change the logic. But if that is not possible, just ignore the linter.

How to get the last birthday year with the date of birth (Python)

I am want to get the last year that someone celebrated his birthday
with his date of birth.
example:
if my date of birth is 12/12/1971
and the date know is 4/12/2021
so my last birthday was in 12/12/2020
so the year is equal to 2020
example2:
if my date of birth is 04/04/2005
and the date know is 4/12/2021
so my last birthday was in 04/04/2021
so the year is equal to 2021
this is my code:
def selfYear(birthdate):
today = date.today()
birthday = birthdate[0]
birthmonth = birthdate[1]
birthyear = birthdate[2]
currentDate = today.strftime("%d/%m/%Y")
currentDate.split('-')
someone can help me figer this out
Compute the current year birthday date, and check if it's already done or not, then return the good year value
def last_birthday(birthdate):
today = date.today()
if birthdate.replace(year=today.year) <= today:
return today.year
return today.year - 1
print(last_birthday(date(1971, 12, 12))) # 2020
print(last_birthday(date(2005, 4, 4))) # 2021
With the auto conversion True -> 1, False -> 0 you could do
def last_birthday(birthdate):
today = date.today()
return today.year - (birthdate.replace(year=today.year) > today)
You can use the date.replace method.
def last_birthday(birthday:date):
current_year = date.today().year
birthday.replace(year=current_year)
if birthday > date.today():
birthday.replace(year=current_year-1)
return birthday.year

Python unittest, datetime

My problem is:
In my following test, everything is working today but not will work tomorrow, I'm a beginner and did try a lot of options, but I failed, I,m trying pass "now" as a parameter but with no success until now.
I have to stop the "datetime.now()" and put one fixed date to can test all variations.
I had god progress until here, but I'm stuck on this
Can you help me, please?
Thank you.
Flavio
import unittest
from datetime import datetime
def get_last_name_and_birthday(name, d):
x = name.split()
dob = d.split("-")
year, month, day = int(dob[2]), int(dob[1]), int(dob[0])
user_birthday = datetime(year, month, day)
return x[-1], user_birthday
def calc_days(user_birthday):
now = datetime.now()
if user_birthday < now:
birthday = datetime(now.year + 1, user_birthday.month, user_birthday.day)
return (birthday - now).days + 1
else:
birthday = datetime(now.year, user_birthday.month, user_birthday.day)
return (birthday - now).days + 1
def generate_output(last_name, cd):
if cd == 365:
return "Hello Mr " + last_name + " Happy Birthday"
elif cd < 365:
return "Hello Mr " + last_name + " your birthday is in " + str(cd) + " days"
else:
return "Hello Mr " + last_name + " your birthday is in " + str(cd - 365) + " days"
def process_name_and_birthday(name, dob):
last_name, user_birthday = get_last_name_and_birthday(name, dob)
cd = calc_days(user_birthday)
return generate_output(last_name, cd)
#name = input("type your full name: ")
#dob = input("type your date of birthday(dd-mm-yy): ")
#print(process_name_and_birthday(name, dob))
class BirthdayTest(unittest.TestCase):
def test_same_day_birthday(self):
self.assertEqual("Hello Mr Oliveira Happy Birthday", process_name_and_birthday("Flavio Oliveira", "11-06-1990"))
class DaysToBirthdayTest(unittest.TestCase):
def test_days_to_birthday(self):
self.assertEqual("Hello Mr Oliveira your birthday is in 9 days", process_name_and_birthday("Flavio Oliveira", "20-06-1978"))
class DaysToPassedBirthdayTest(unittest.TestCase):
def test_how_many_days_passed_birthday(self):
self.assertEqual("Hello Mr Oliveira your birthday is in 364 days", process_name_and_birthday("Flavio Oliveira", "10-06-1978"))
unittest.main()
Add the following three lines under your import of datetime:
from unittest.mock import Mock
datetime = Mock(wraps=datetime)
datetime.now.return_value = datetime(2020, 6, 11, 20)
There is more information about the mock module here: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock

Admission price based on age

I'm trying to come up with a program where you can calculate the admission price based on age. The prices are: 14 and under ($5.00), 15 to 64 ($9.00), and 65 and over ($7.50). The customer may also have a coupon that will take a dollar off of their price. So far I have come up with:
print ("Hello, welcome to Hopper's Computer Museum! To determine your enterance fee, please enter the following:")
print ('Your Date of Birth (mm dd yyyy)')
Date_of_Birth = input("--->")
print ('Todays Date: (mm dd yyyy)')
Todays_Date = input("--->")
age = (tYear-bYear)
if (bMonth > tMonth):
age == age-1
if (bMonth == tMonth and
bDay > tDay):
age == age-1
price = -1
while price == -1:
try:
age = int(input('age:'))
excpet ValueError:
print("Not a number, try again.")
continue
if age <= 14:
price==5.00
elif age > 15 and age < 64:
price==9.00
else age > 65:
price==7.50
print ('Do you have a coupon (y/n)?')
Discount = input("--->")
if Discount == "y" or Discount == "Y":
price = price-1
elif Discount == "n" or Discount == "N":
price = price
print ('Your admission fee is '+str(price)')
One thing that I am confused on would be how to get Python to take the dates that the user inputs and put it into the age calculation that I set up.
you can specify the format in which you want to take date and then split it like ...
import datetime
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
Or you can refer the following links for more info...
getting-input-date-from-the-user-in-python-using-datetime-datetime
how-to-have-user-input-date-and-subtract-from-it
how-do-i-take-input-in-the-date-time-format
If you want to have a fixed format in which user will provide the date like dd/mm/yyyy or mm/dd/yyyy
Then you can simply use:
import datetime
date_time_object = datetime.datetime.strptime(date_provided, date_format)
#date_provided = '12/01/1995'
#date_format = '%d/%m/%Y'
curr_time = datetime.datetime.now()
time_diff = curr_time - date_time_object
print time_diff
age_days = time_diff.days
age_years = age_days / 326.25
print age_years

Checking the format/contents of a string

This program is intended to ask for the date as dd/mm/yyyy. It should then check to see if the user inputted the date in the correct format (dd/mm/yyyy). My program is not able to recognize the format correctly. This is my program:
date = (input("enter the date as dd/mm/yyyy: "))
date = day, month, year = date.split("/")
if date == (day + '/' + month + '/' + year):
print (date)
if len(day) == 1 or len(day) == 2:
print("1")
if len(month) == 1 or len(month) == 2:
print("2")
if len(year) == 4:
print ("3")
else:
if len(day) == 1 or len(day) == 2:
print("4")
if len(month) == 1 or len(month) == 2:
print("5")
if len(year) == 4:
print ("6")
The numbers being printed currently have no other purpose than to just check the validity of the date. So far, only 4,5, and 6 are being printed, meaning my program is not recognizing the formatting of the date.
Your solution doesn't work because date=day, month, year = date.split("/") sets date to a list, then you're comparing it to a string (day + '/' + month + '/' + year). However, your solution is a solved problem, do instead:
import datetime
date = (input("enter the date as dd/mm/yyyy: "))
try: datetime.datetime.strptime(date,"%d/%m/%Y")
except ValueError: # incorrect format
In addition, you probably are turning this into a datetime object later on anyway, so you can do so in the try block!
As a further optimization, be aware that many users won't WANT to enter their dates using / as a datesep! Do some introspection on your input, and adjust your datesep appropriately.
date = input("enter the date: ")
if "-" in date: datesep = "-"
elif "/" in date: datesep = "/"
elif "." in date: datesep = "."
else: datesep = ""
if len(date) < 6: yeartype = "%y"
elif date[-4:-2] not in ("19","20"): yeartype = "%y"
else: yeartype = "%Y"
try: date = datetime.datetime.strptime(date,"%d{0}%m{0}{1}".format(datesep,yeartype))
except ValueError: # invalid date
Now your code will end up with a valid datetime object of Feb 2nd 2014 for:
02022014
222014
0222014
222014
020214
02214
2214
02-02-2014
02/02/2014
2-2-14
2/2/2014
2/2/14
etc etc etc
You can use the datetime module:
import datetime
def checkdate(date):
try:
datelist = date.split('/')
datetime.datetime(year=int(datelist[2]), month=int(datelist[1]),day=int(datelist[0]))
return True
except:
return False

Categories

Resources