Home > Net >  How do I calculate the days left in a year using a function?
How do I calculate the days left in a year using a function?

Time:03-31

I want to calculate the days left in a year using a function in python.

I don't want to use the date.time library because it isn't something I should use, instead I should create a function that will do this.

Could I somehow implement these functions:

def is_leap_year(year):
    return (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)

def days_in_month(month, year):

    if month in ['September', 'April', 'June', 'November']:
        print(30)

    elif month in ['January', 'March', 'May', 'July', 'August','October','December']:
        print(31)        

    elif month == 'February' and is_leap_year(year) == True:
        print(29)

    elif month == 'February' and is_leap_year(year) == False:
        print(28)

    else:
        print(None)

To create the last function I am having trouble with?

Edit:

def is_leap_year(year):
    if year == (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0):
         return 366
    else:
        return 365



def days_in_month(month, year):

    if month in ['September', 'April', 'June', 'November']:
        print(30)

    elif month in ['January', 'March', 'May', 'July', 
'August','October','December']:
        print(31)        

    elif month == 'February' and is_leap_year(year) == True:
        print(29)

    elif month == 'February' and is_leap_year(year) == False:
        print(28)

    else:
        print(None)

def days_left_in_year(month, day, year):
    if is_leap_year == 366:
        days_left = 366 - day
    if is_leap_year == 365:
        day_left = 366 - day

CodePudding user response:

There is no legitimate reason NOT to use the built-in modules for this. The whole reason they exist is to eliminate the possibility of introducing difficult-to-find bugs, and date/time/leap-year computation are among the most error-prone that a programmer is likely to encounter.

import datetime
def days_left_in_year(month, day, year):
   day_of_year = datetime.datetime(year,month,day).timetuple().tm_yday
   end_of_year = datetime.datetime(year,12,31).timetuple().tm_yday
   return end_of_year - day_of_year

CodePudding user response:

If you really don't want to use standard modules (e.g., datetime) then you could do this:

diysf = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]

def isleap(yy):
    return yy % 400 == 0 or (yy % 100 != 0 and yy % 4 == 0)

def rdays(yy, mm, dd):
    diy = 366 if mm < 3 and isleap(yy) else 365
    return diy - diysf[mm-1] - dd

print(rdays(YY,MM,DD))

Output:

276
  • Related