Age from birthdate in python - python

How can I find an age in python from today's date and a persons birthdate? The birthdate is a from a DateField in a Django model.

That can be done much simpler considering that int(True) is 1 and int(False) is 0, and tuples comparison goes from left to right:
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

from datetime import date
def calculate_age(born):
today = date.today()
try:
birthday = born.replace(year=today.year)
except ValueError: # raised when birth date is February 29 and the current year is not a leap year
birthday = born.replace(year=today.year, month=born.month+1, day=1)
if birthday > today:
return today.year - born.year - 1
else:
return today.year - born.year
Update: Use Danny's solution, it's better

from datetime import date
days_in_year = 365.2425
age = int((date.today() - birth_date).days / days_in_year)
In Python 3, you could perform division on datetime.timedelta:
from datetime import date, timedelta
age = (date.today() - birth_date) // timedelta(days=365.2425)

As suggested by #[Tomasz Zielinski] and #Williams python-dateutil can do it just 5 lines.
from dateutil.relativedelta import *
from datetime import date
today = date.today()
dob = date(1982, 7, 5)
age = relativedelta(today, dob)
>>relativedelta(years=+33, months=+11, days=+16)`

The simplest way is using python-dateutil
import datetime
import dateutil
def birthday(date):
# Get the current date
now = datetime.datetime.utcnow()
now = now.date()
# Get the difference between the current date and the birthday
age = dateutil.relativedelta.relativedelta(now, date)
age = age.years
return age

from datetime import date
def age(birth_date):
today = date.today()
y = today.year - birth_date.year
if today.month < birth_date.month or today.month == birth_date.month and today.day < birth_date.day:
y -= 1
return y

Unfortunately, you cannot just use timedelata as the largest unit it uses is day and leap years will render you calculations invalid. Therefore, let's find number of years then adjust by one if the last year isn't full:
from datetime import date
birth_date = date(1980, 5, 26)
years = date.today().year - birth_date.year
if (datetime.now() - birth_date.replace(year=datetime.now().year)).days >= 0:
age = years
else:
age = years - 1
Upd:
This solution really causes an exception when Feb, 29 comes into play. Here's correct check:
from datetime import date
birth_date = date(1980, 5, 26)
today = date.today()
years = today.year - birth_date.year
if all((x >= y) for x,y in zip(today.timetuple(), birth_date.timetuple()):
age = years
else:
age = years - 1
Upd2:
Calling multiple calls to now() a performance hit is ridiculous, it does not matter in all but extremely special cases. The real reason to use a variable is the risk of data incosistency.

If you're looking to print this in a page using django templates, then the following might be enough:
{{ birth_date|timesince }}

The classic gotcha in this scenario is what to do with people born on the 29th day of February. Example: you need to be aged 18 to vote, drive a car, buy alcohol, etc ... if you are born on 2004-02-29, what is the first day that you are permitted to do such things: 2022-02-28, or 2022-03-01? AFAICT, mostly the first, but a few killjoys might say the latter.
Here's code that caters for the 0.068% (approx) of the population born on that day:
def age_in_years(from_date, to_date, leap_day_anniversary_Feb28=True):
age = to_date.year - from_date.year
try:
anniversary = from_date.replace(year=to_date.year)
except ValueError:
assert from_date.day == 29 and from_date.month == 2
if leap_day_anniversary_Feb28:
anniversary = datetime.date(to_date.year, 2, 28)
else:
anniversary = datetime.date(to_date.year, 3, 1)
if to_date < anniversary:
age -= 1
return age
if __name__ == "__main__":
import datetime
tests = """
2004 2 28 2010 2 27 5 1
2004 2 28 2010 2 28 6 1
2004 2 28 2010 3 1 6 1
2004 2 29 2010 2 27 5 1
2004 2 29 2010 2 28 6 1
2004 2 29 2010 3 1 6 1
2004 2 29 2012 2 27 7 1
2004 2 29 2012 2 28 7 1
2004 2 29 2012 2 29 8 1
2004 2 29 2012 3 1 8 1
2004 2 28 2010 2 27 5 0
2004 2 28 2010 2 28 6 0
2004 2 28 2010 3 1 6 0
2004 2 29 2010 2 27 5 0
2004 2 29 2010 2 28 5 0
2004 2 29 2010 3 1 6 0
2004 2 29 2012 2 27 7 0
2004 2 29 2012 2 28 7 0
2004 2 29 2012 2 29 8 0
2004 2 29 2012 3 1 8 0
"""
for line in tests.splitlines():
nums = [int(x) for x in line.split()]
if not nums:
print
continue
datea = datetime.date(*nums[0:3])
dateb = datetime.date(*nums[3:6])
expected, anniv = nums[6:8]
age = age_in_years(datea, dateb, anniv)
print datea, dateb, anniv, age, expected, age == expected
Here's the output:
2004-02-28 2010-02-27 1 5 5 True
2004-02-28 2010-02-28 1 6 6 True
2004-02-28 2010-03-01 1 6 6 True
2004-02-29 2010-02-27 1 5 5 True
2004-02-29 2010-02-28 1 6 6 True
2004-02-29 2010-03-01 1 6 6 True
2004-02-29 2012-02-27 1 7 7 True
2004-02-29 2012-02-28 1 7 7 True
2004-02-29 2012-02-29 1 8 8 True
2004-02-29 2012-03-01 1 8 8 True
2004-02-28 2010-02-27 0 5 5 True
2004-02-28 2010-02-28 0 6 6 True
2004-02-28 2010-03-01 0 6 6 True
2004-02-29 2010-02-27 0 5 5 True
2004-02-29 2010-02-28 0 5 5 True
2004-02-29 2010-03-01 0 6 6 True
2004-02-29 2012-02-27 0 7 7 True
2004-02-29 2012-02-28 0 7 7 True
2004-02-29 2012-02-29 0 8 8 True
2004-02-29 2012-03-01 0 8 8 True

import datetime
Todays date
td=datetime.datetime.now().date()
Your birthdate
bd=datetime.date(1989,3,15)
Your age
age_years=int((td-bd).days /365.25)

Expanding on Danny's Solution, but with all sorts of ways to report ages for younger folk (note, today is datetime.date(2015,7,17)):
def calculate_age(born):
'''
Converts a date of birth (dob) datetime object to years, always rounding down.
When the age is 80 years or more, just report that the age is 80 years or more.
When the age is less than 12 years, rounds down to the nearest half year.
When the age is less than 2 years, reports age in months, rounded down.
When the age is less than 6 months, reports the age in weeks, rounded down.
When the age is less than 2 weeks, reports the age in days.
'''
today = datetime.date.today()
age_in_years = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
months = (today.month - born.month - (today.day < born.day)) %12
age = today - born
age_in_days = age.days
if age_in_years >= 80:
return 80, 'years or older'
if age_in_years >= 12:
return age_in_years, 'years'
elif age_in_years >= 2:
half = 'and a half ' if months > 6 else ''
return age_in_years, '%syears'%half
elif months >= 6:
return months, 'months'
elif age_in_days >= 14:
return age_in_days/7, 'weeks'
else:
return age_in_days, 'days'
Sample code:
print '%d %s' %calculate_age(datetime.date(1933,6,12)) # >=80 years
print '%d %s' %calculate_age(datetime.date(1963,6,12)) # >=12 years
print '%d %s' %calculate_age(datetime.date(2010,6,19)) # >=2 years
print '%d %s' %calculate_age(datetime.date(2010,11,19)) # >=2 years with half
print '%d %s' %calculate_age(datetime.date(2014,11,19)) # >=6 months
print '%d %s' %calculate_age(datetime.date(2015,6,4)) # >=2 weeks
print '%d %s' %calculate_age(datetime.date(2015,7,11)) # days old
80 years or older
52 years
5 years
4 and a half years
7 months
6 weeks
7 days

Here is a solution to find age of a person as either years or months or days.
Lets say a person's date of birth is 2012-01-17T00:00:00
Therefore, his age on 2013-01-16T00:00:00 will be 11 months
or if he is born on 2012-12-17T00:00:00,
his age on 2013-01-12T00:00:00 will be 26 days
or if he is born on 2000-02-29T00:00:00,
his age on 2012-02-29T00:00:00 will be 12 years
You will need to import datetime.
Here is the code:
def get_person_age(date_birth, date_today):
"""
At top level there are three possibilities : Age can be in days or months or years.
For age to be in years there are two cases: Year difference is one or Year difference is more than 1
For age to be in months there are two cases: Year difference is 0 or 1
For age to be in days there are 4 possibilities: Year difference is 1(20-dec-2012 - 2-jan-2013),
Year difference is 0, Months difference is 0 or 1
"""
years_diff = date_today.year - date_birth.year
months_diff = date_today.month - date_birth.month
days_diff = date_today.day - date_birth.day
age_in_days = (date_today - date_birth).days
age = years_diff
age_string = str(age) + " years"
# age can be in months or days.
if years_diff == 0:
if months_diff == 0:
age = age_in_days
age_string = str(age) + " days"
elif months_diff == 1:
if days_diff < 0:
age = age_in_days
age_string = str(age) + " days"
else:
age = months_diff
age_string = str(age) + " months"
else:
if days_diff < 0:
age = months_diff - 1
else:
age = months_diff
age_string = str(age) + " months"
# age can be in years, months or days.
elif years_diff == 1:
if months_diff < 0:
age = months_diff + 12
age_string = str(age) + " months"
if age == 1:
if days_diff < 0:
age = age_in_days
age_string = str(age) + " days"
elif days_diff < 0:
age = age-1
age_string = str(age) + " months"
elif months_diff == 0:
if days_diff < 0:
age = 11
age_string = str(age) + " months"
else:
age = 1
age_string = str(age) + " years"
else:
age = 1
age_string = str(age) + " years"
# The age is guaranteed to be in years.
else:
if months_diff < 0:
age = years_diff - 1
elif months_diff == 0:
if days_diff < 0:
age = years_diff - 1
else:
age = years_diff
else:
age = years_diff
age_string = str(age) + " years"
if age == 1:
age_string = age_string.replace("years", "year").replace("months", "month").replace("days", "day")
return age_string
Some extra functions used in the above codes are:
def get_todays_date():
"""
This function returns todays date in proper date object format
"""
return datetime.now()
And
def get_date_format(str_date):
"""
This function converts string into date type object
"""
str_date = str_date.split("T")[0]
return datetime.strptime(str_date, "%Y-%m-%d")
Now, we have to feed get_date_format() with the strings like 2000-02-29T00:00:00
It will convert it into the date type object which is to be fed to get_person_age(date_birth, date_today).
The function get_person_age(date_birth, date_today) will return age in string format.

As I did not see the correct implementation, I recoded mine this way...
def age_in_years(from_date, to_date=datetime.date.today()):
if (DEBUG):
logger.debug("def age_in_years(from_date='%s', to_date='%s')" % (from_date, to_date))
if (from_date>to_date): # swap when the lower bound is not the lower bound
logger.debug('Swapping dates ...')
tmp = from_date
from_date = to_date
to_date = tmp
age_delta = to_date.year - from_date.year
month_delta = to_date.month - from_date.month
day_delta = to_date.day - from_date.day
if (DEBUG):
logger.debug("Delta's are : %i / %i / %i " % (age_delta, month_delta, day_delta))
if (month_delta>0 or (month_delta==0 and day_delta>=0)):
return age_delta
return (age_delta-1)
Assumption of being "18" on the 28th of Feb when born on the 29th is just wrong.
Swapping the bounds can be left out ... it is just a personal convenience for my code :)

Extend to Danny W. Adair Answer, to get month also
def calculate_age(b):
t = date.today()
c = ((t.month, t.day) < (b.month, b.day))
c2 = (t.day< b.day)
return t.year - b.year - c,c*12+t.month-b.month-c2

import datetime
def age(date_of_birth):
if date_of_birth > datetime.date.today().replace(year = date_of_birth.year):
return datetime.date.today().year - date_of_birth.year - 1
else:
return datetime.date.today().year - date_of_birth.year
In your case:
import datetime
# your model
def age(self):
if self.birthdate > datetime.date.today().replace(year = self.birthdate.year):
return datetime.date.today().year - self.birthdate.year - 1
else:
return datetime.date.today().year - self.birthdate.year

Slightly modified Danny's solution for easier reading and understanding
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = today.year - birth_date.year
full_year_passed = (today.month, today.day) < (birth_date.month, birth_date.day)
if not full_year_passed:
age -= 1
return age

A slightly more elegant solution than #DannyWAdairs solution might be to work with the .timetuple() method [Python-doc]:
from datetime import date
def calculate_age(born):
today = date.today()
return today.year - born.year - (today.timetuple()[1:3] < born.timetuple()[1:3])
You can easily use this to generalize this further to increase its granularity to seconds, such that the age increments if it is greater than or equal to the number of seconds of that day, if born is for example a datetime object:
from datetime import datetime
def calculate_age_with_seconds(born):
today = datetime.now()
return today.year - born.year - (today.timetuple()[1:6] < born.timetuple()[1:6])
This will work for born both being a date or a datetime object.

serializers.py
age = serializers.SerializerMethodField('get_age')
class Meta:
model = YourModel
fields = [..,'','birthdate','age',..]
import datetime
def get_age(self, instance):
return datetime.datetime.now().year - instance.birthdate.year

You can use Python 3 to do all this. Just run the following code and see.
# Creating a variables:
greeting = "Hello, "
name = input("what is your name?")
birth_year = input("Which year you were born?")
response = "Your age is "
# Converting string variable to int:
calculation = 2020 - int(birth_year)
# Printing:
print(f'{greeting}{name}. {response}{calculation}')

Related

python nested while loops and datetime

I'm teaching myself python to ATBS. Instead of spending 45 minutes typing out a bunch of repetitive data in excel I've spent the past 90 failing to write a simple calendar script.
Starting with the values "2012-09-01" and "2012-09-30" I want to each line to increase the month value by 1 it hits 12 and at which point the year value advances by 1, until the date 2018-12-31.
e.g.
"2012-09-01 2012-09-30
2012-10-01 2012-10-31
2012-11-01 2012-11-30
2012-12-01 2012-12-31"
Here's my code, which stops at 2012-12-31.
import datetime
year = 2012
month = 9
day_start = 1
day_end = 31
while year <= 2018:
while month <= 12:
if month == 4 or month == 6 or month == 9 or month == 11:
day_end = 30
else:
day_end = 31
print(datetime.date(year, month, day_start), " ", datetime.date(year, month, day_end))
month = month + 1
year = year + 1
Any help is much appreciated!
Check this out. Using the calendar library to detect leap years.
import datetime
import calendar
year = 2012
month = 9
day_start = 1
day_end = 31
while year <= 2018:
while month <= 12:
if month == 4 or month == 6 or month == 9 or month == 11:
day_end = 30
elif month == 2:
day_end = 29 if calendar.isleap(year) else 28
else:
day_end = 31
print(datetime.date(year, month, day_start), " ", datetime.date(year, month, day_end))
month = month + 1
year = year + 1
month = 1
Line
if month == 4 or month == 6 or month == 9 or month == 11:
can be abbreviated to:
if month in (4, 6, 9, 11):

I need to write a function to print out a week of a given month, with the arguments week number, start day and days in the month (Python)

Given a week number, (1st, 2nd, …), the day on which the 1st of the month falls (1 for Monday, 2 for Tuesday, …), and the number of days in the month: return a string consisting of the day of the month for each day in that week, starting with Monday and ending with Sunday. Week number represents the weeks in the months.
I have done the following functions:
My code for these functions are below.
import datetime
from datetime import datetime
import calendar
from datetime import date
def week(week_num, start_day, days_in_month):
week_string = ""
if week_num == 1:
if start_day == 1:
week_string = "1 2 3 4 5 6 7"
elif start_day == 2:
week_string = " 1 2 3 4 5 6"
elif start_day == 3:
week_string = " 1 2 3 4 5"
elif start_day == 4:
week_string = " 1 2 3 4"
elif start_day == 5:
week_string = " 1 2 3"
elif start_day == 6:
week_string = " 1 2"
elif start_day == 7:
week_string = " 1"
elif week_num == 2:
if start_day == 1:
week_string = "8 9 10 11 12 13 14"
elif start_day == 2:
week_string = "7 8 9 10 11 12 13"
elif start_day == 3:
week_string = "6 7 8 9 10 11 12"
elif start_day == 4:
#carry on in the above way, but this doesn't seem efficient
return week_string
def main():
month_name = input("Enter month:\n")
year = eval(input("Enter year:\n"))
if __name__=='__main__':
main()
Does anyone have any ideas on how to do the function? I need to return a string value
Another idea I had:
def week(week_num, start_day, days_in_month):
week_string = ""
if week_num == 1:
week_string = ""
day = start_day
for i in range(1, 8 -start_day+1):
week_string = week_string + str(i) + " "
week_string = "{0:<20}".format(week_string)
return week_string
An example of the input and output of this function:
week(1, 3, 30)
returns the string
' 1 2 3 4 5'
week(2, 3, 30)
returns the string
' 6 7 8 9 10 11 12’
edit: you heavily altered your question, I'll update my response once I'll understand what you need
datetime and calendar modules should supply you with all you need
from datetime import datetime
import calendar
# is leapyear
calendar.isleap(2020) # True
# just add +1 if you need it in the format that you want
datetime.strptime('25.2.2020', '%d.%m.%Y').weekday() # = 1 = Tuesday
# from name to month number
datetime.strptime('february', '%B').month # = 2
# days in month and weekday of starting month
# with the starting weekday you can easily calculate the number of weeks
calendar.monthrange(2020,2) # = (5, 29), 5=saturday, 29 days in month
Some general remarks to your code:
You can use 'January'.upper() to convert it to 'JANUARY' and only need to check month_name=='JANUARY' and save you the redundant comparison
You can use if month_num in [1,3,5,7,8,10,12]: to make it more readable

Map column birthdates in python pandas df to astrology signs

I have a dataframe with a column that includes individuals' birthdays. I would like to map that column to the individuals' astrology sign using code I found (below). I am having trouble writing the code to creat the variables.
My current dataframe looks like this
birthdate answer YEAR MONTH-DAY
1970-03-31 5 1970 03-31
1970-05-25 9 1970 05-25
1970-06-05 3 1970 06-05
1970-08-28 2 1970 08-28
The code I found that creates a function to map the dates is available at this website: https://www.geeksforgeeks.org/program-display-astrological-sign-zodiac-sign-given-date-birth/
Any tips would be appreciated.
Change previous answer by Series.dt.month_name with lowercase strings:
def zodiac_sign(day, month):
# checks month and date within the valid range
# of a specified zodiac
if month == 'december':
return 'Sagittarius' if (day < 22) else 'capricorn'
elif month == 'january':
return 'Capricorn' if (day < 20) else 'aquarius'
elif month == 'february':
return 'Aquarius' if (day < 19) else 'pisces'
elif month == 'march':
return 'Pisces' if (day < 21) else 'aries'
elif month == 'april':
return 'Aries' if (day < 20) else 'taurus'
elif month == 'may':
return 'Taurus' if (day < 21) else 'gemini'
elif month == 'june':
return 'Gemini' if (day < 21) else 'cancer'
elif month == 'july':
return 'Cancer' if (day < 23) else 'leo'
elif month == 'august':
return 'Leo' if (day < 23) else 'virgo'
elif month == 'september':
return 'Virgo' if (day < 23) else 'libra'
elif month == 'october':
return 'Libra' if (day < 23) else 'scorpio'
elif month == 'november':
return 'scorpio' if (day < 22) else 'sagittarius'
dates = pd.to_datetime(astrology['birthdate'])
y = dates.dt.year
now = pd.to_datetime('now').year
astrology = astrology.assign(month = dates.dt.month_name().str.lower(),
day = dates.dt.day,
year = y.mask(y > now, y - 100))
print (astrology)
birthdate answer YEAR MONTH-DAY month day year
0 1970-03-31 5 1970 03-31 march 31 1970
1 1970-05-25 9 1970 05-25 may 25 1970
2 1970-06-05 3 1970 06-05 june 5 1970
3 1970-08-28 2 1970 08-28 august 28 1970
astrology['sign'] = astrology.apply(lambda x: zodiac_sign(x['day'], x['month']), axis=1)
print (astrology)
birthdate answer YEAR MONTH-DAY month day year sign
0 1970-03-31 5 1970 03-31 march 31 1970 aries
1 1970-05-25 9 1970 05-25 may 25 1970 gemini
2 1970-06-05 3 1970 06-05 june 5 1970 Gemini
3 1970-08-28 2 1970 08-28 august 28 1970 virgo
You can apply the zodiac_sign function to the dataframe as -
import pandas as pd
from io import StringIO
# Sample
x = StringIO("""birthdate,answer,YEAR,MONTH-DAY
1970-03-31,5,1970,03-31
1970-05-25,9,1970,05-25
1970-06-05,3,1970,06-05
1970-08-28,2,1970,08-28
""")
df = pd.read_csv(x, sep=',')
df['birthdate'] = pd.to_datetime(df['birthdate'])
df['zodiac_sign'] = df['birthdate'].apply(lambda x: zodiac_sign(x.day, x.strftime("%B").lower()))
print(df)
Output:
birthdate answer YEAR MONTH-DAY zodiac_sign
0 1970-03-31 5 1970 03-31 aries
1 1970-05-25 9 1970 05-25 gemini
2 1970-06-05 3 1970 06-05 Gemini
3 1970-08-28 2 1970 08-28 virgo

How do I get an age in years and date on pandas

Here's my data
Customer_id Date-of-birth
1 1992-07-02
2 1991-07-03
Here's my code
import datetime as dt
df['now'] = dt.datetime.now()
df['age'] = df['now'].dt.date - df['Date-of-birth']
Here's the result
Customer_id Date-of-birth age
1 1992-07-02 xxxx days
2 1991-07-03 xxxx days
The result that I want is
Customer_id Date-of-birth age
1 1992-07-02 26 years 22 days
2 1991-07-03 27 years 21 days
Just let you now, by df.dtypes, Date-of-birth is an object because is based on customer input in dropdown
How can I achieve this? I hope the question is clear enough
Use this solution with custom function, because count it is not easy because leaps years:
from dateutil.relativedelta import relativedelta
def f(end):
r = relativedelta(pd.to_datetime('now'), end)
return '{} years {} days'.format(r.years, r.days)
df['age'] = df["Date-of-birth"].apply(f)
print (df)
Customer_id Date-of-birth age
0 1 1992-07-02 26 years 22 days
1 2 1991-07-03 27 years 21 days
Input:
import pandas as pd
import datetime as dt
now = dt.datetime.now()
for i in range(0, len(df)):
diff = now - dt.datetime.strptime(df['Date-of-Birth'][i], '%Y-%m-%d')
years = diff.days // 365
days = diff.days - (years*365)
df['age'][i] = str(years) + ' years ' + str(days) + ' days'
print(df)
Output:
Customer_id Date-of-Birth age
1 1992-07-04 26 years 25 days
2 1991-07-04 27 years 26 days
Maybe you could use something like the following. Note that it relies on the fact that the average year has 365.25 days, so it may be a day off sometimes.
import datetime as dt
def year_days_diff(x):
diff = (dt.datetime.now() - x).days
return str(int(diff / 365.25)) + ' years ' + str(int(diff / 365.25 % 1 * 365.25)) + ' days'
Example:
birth_date = dt.datetime.now() - dt.timedelta(10000)
year_days_diff(birth_date)
output:
'27 years 138 days'
This could give you age by rounding to years.
ref_date = dt.datetime.now()
df['age'] = df['Date-of-birth'].apply(lambda x: len(pd.date_range(start = x, end = ref_date, freq = 'Y')))
Use astype('<m8[Y]')
Ex:
df['age'] = (pd.to_datetime('now') - df['Date-of-birth']).astype('<m8[Y]')
Demo:
import pandas as pd
df = pd.DataFrame({"Date-of-birth": pd.to_datetime(['1992-07-24', '1991-07-24'])})
df["age"] = (pd.to_datetime('now') - df["Date-of-birth"]).astype('<m8[Y]')
print(df)
Output:
Date-of-birth age
0 1992-07-24 25.0
1 1991-07-24 27.0

Trying to make a program that displays days in a month

I'm trying to write a program that shows the days in a month when you type the number that corresponds to the month.
Ex. 1 = January, would print "31"
This is what I have and it seems logical to me. Although I'm just over a month into this and I have no idea what I'm doing.
def calcDaysInMonth():
(list,(range,(1, 12)))
a = raw_input()
int(a)
jan = 1
feb = 2
mar = 3
apr = 4
may = 5
june = 6
july = 7
aug = 8
sept = 9
octo = 10
nov = 11
dec = 12
if jan is True:
print("31")
using static number wont help you get correct result. because Feb days in leap year is different than normal. so use
$Year = 2017
$month = 08`
echo cal_days_in_month(CAL_GREGORIAN, (int)$month, $Year);
The reason your code isn't working is because you're assigning the input to a but you're never checking the value of a and using that to determine what should be printed (you're simply assigning integers to variables called jan, feb etc)
You're looking for something like this:
a = int(raw_input())
if a == 1:
print("31 days")
elif a == 2:
print("28 days")
# just repeat with elif until december/12
You could try to get clever with it with dictionaries to map months to days or something, but really a more sensible solution would be the following...
Due to February having a different number of days given leap years, it makes more sense to just use calendar.monthrange to get the number of days in a month for any given year:
from calendar import monthrange
year = 2017
a = int(raw_input())
num_days = monthrange(year, a)[1]
print("{} days".format(num_days))
Thank you for all your help guys.
My class now has an answer for what we were doing. What was wanted:
month = int(raw_input())
day = 0
def calcDays(month):
if month ==1:
days = 31
print 31
if month==2:
days = 28
print 28
if month == 3:
days = 31
print 31
if month == 4:
days = 30
print 30
if month==5:
days = 31
print 31
if month ==6:
days = 30
print 30
if month==7:
days = 31
print 31
if month ==8:
days = 31
print 31
if month==9:
days = 30
print 30

Categories

Resources