Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (1.6k points)

How can I get the number of days in a current month?

Ex-

Suppose user inputs Jan 2012 then it should give 31 as output

and if the input is Feb 2012 then the output should be 29.

1 Answer

0 votes
by (260 points)

import calendar
'''
returns the number of days for a month, year
'''
def get_nb_days(str_date):

    # maps the month name abbreviation to the month number
    dict_months = {v: k for k,v in     enumerate(calendar.month_abbr)}

    # extracts the month and year from the input date
    str_month , str_year = str_date.split(' ')
    year = int(str_year)
    month = dict_months[str_month]

    # gives the number of days for year month
    nb_days = calendar.monthrange(year,month)[1]

    return nb_days

Hope my answer helps !

Related questions

Browse Categories

...