How to get the last day of the month?

后端 未结 30 2644
迷失自我
迷失自我 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:58

    Another solution would be to do something like this:

    from datetime import datetime
    
    def last_day_of_month(year, month):
        """ Work out the last day of the month """
        last_days = [31, 30, 29, 28, 27]
        for i in last_days:
            try:
                end = datetime(year, month, i)
            except ValueError:
                continue
            else:
                return end.date()
        return None
    

    And use the function like this:

    >>> 
    >>> last_day_of_month(2008, 2)
    datetime.date(2008, 2, 29)
    >>> last_day_of_month(2009, 2)
    datetime.date(2009, 2, 28)
    >>> last_day_of_month(2008, 11)
    datetime.date(2008, 11, 30)
    >>> last_day_of_month(2008, 12)
    datetime.date(2008, 12, 31)
    

提交回复
热议问题