How to get the last day of the month?

后端 未结 30 2588
迷失自我
迷失自我 2020-11-22 06:13

Is there a way using Python\'s standard library to easily determine (i.e. one function call) the last day of a given month?

If the standard library doesn\'t support

相关标签:
30条回答
  • 2020-11-22 07:11

    In the code below 'get_last_day_of_month(dt)' will give you this, with date in string format like 'YYYY-MM-DD'.

    import datetime
    
    def DateTime( d ):
        return datetime.datetime.strptime( d, '%Y-%m-%d').date()
    
    def RelativeDate( start, num_days ):
        d = DateTime( start )
        return str( d + datetime.timedelta( days = num_days ) )
    
    def get_first_day_of_month( dt ):
        return dt[:-2] + '01'
    
    def get_last_day_of_month( dt ):
        fd = get_first_day_of_month( dt )
        fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
        return RelativeDate( fd_next_month, -1 )
    
    0 讨论(0)
  • 2020-11-22 07:11

    Here is a long (easy to understand) version but takes care of leap years.

    cheers, JK

    def last_day_month(year, month):
        leap_year_flag = 0
        end_dates = {
            1: 31,
            2: 28,
            3: 31,
            4: 30,
            5: 31,
            6: 30,
            7: 31,
            8: 31,
            9: 30,
            10: 31,
            11: 30,
            12: 31
        }
    
        # Checking for regular leap year    
        if year % 4 == 0:
            leap_year_flag = 1
        else:
            leap_year_flag = 0
    
        # Checking for century leap year    
        if year % 100 == 0:
            if year % 400 == 0:
                leap_year_flag = 1
            else:
                leap_year_flag = 0
        else:
            pass
    
        # return end date of the year-month
        if leap_year_flag == 1 and month == 2:
            return 29
        elif leap_year_flag == 1 and month != 2:
            return end_dates[month]
        else:
            return end_dates[month]
    
    0 讨论(0)
  • 2020-11-22 07:12

    EDIT: See @Blair Conrad's answer for a cleaner solution


    >>> import datetime
    >>> datetime.date(2000, 2, 1) - datetime.timedelta(days=1)
    datetime.date(2000, 1, 31)
    
    0 讨论(0)
  • 2020-11-22 07:12

    Here is another answer. No extra packages required.

    datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1)
    

    Get the first day of the next month and subtract a day from it.

    0 讨论(0)
  • 2020-11-22 07:14

    This is actually pretty easy with dateutil.relativedelta (package python-datetutil for pip). day=31 will always always return the last day of the month.

    Example:

    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    
    date_in_feb = datetime.datetime(2013, 2, 21)
    print datetime.datetime(2013, 2, 21) + relativedelta(day=31)  # End-of-month
    >>> datetime.datetime(2013, 2, 28, 0, 0)
    
    0 讨论(0)
  • 2020-11-22 07:14

    EDIT: see my other answer. It has a better implementation than this one, which I leave here just in case someone's interested in seeing how one might "roll your own" calculator.

    @John Millikin gives a good answer, with the added complication of calculating the first day of the next month.

    The following isn't particularly elegant, but to figure out the last day of the month that any given date lives in, you could try:

    def last_day_of_month(date):
        if date.month == 12:
            return date.replace(day=31)
        return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)
    
    >>> last_day_of_month(datetime.date(2002, 1, 17))
    datetime.date(2002, 1, 31)
    >>> last_day_of_month(datetime.date(2002, 12, 9))
    datetime.date(2002, 12, 31)
    >>> last_day_of_month(datetime.date(2008, 2, 14))
    datetime.date(2008, 2, 29)
    
    0 讨论(0)
提交回复
热议问题