How to get the last day of the month?

后端 未结 30 2596
迷失自我
迷失自我 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 06:51

    You can calculate the end date yourself. the simple logic is to subtract a day from the start_date of next month. :)

    So write a custom method,

    import datetime
    
    def end_date_of_a_month(date):
    
    
        start_date_of_this_month = date.replace(day=1)
    
        month = start_date_of_this_month.month
        year = start_date_of_this_month.year
        if month == 12:
            month = 1
            year += 1
        else:
            month += 1
        next_month_start_date = start_date_of_this_month.replace(month=month, year=year)
    
        this_month_end_date = next_month_start_date - datetime.timedelta(days=1)
        return this_month_end_date
    

    Calling,

    end_date_of_a_month(datetime.datetime.now().date())
    

    It will return the end date of this month. Pass any date to this function. returns you the end date of that month.

提交回复
热议问题