How to get the last day of the month?

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

提交回复
热议问题