How to get the last day of the month?

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

    I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information:

    monthrange(year, month)
        Returns weekday of first day of the month and number of days in month, for the specified year and month.

    >>> import calendar
    >>> calendar.monthrange(2002,1)
    (1, 31)
    >>> calendar.monthrange(2008,2)
    (4, 29)
    >>> calendar.monthrange(2100,2)
    (0, 28)
    

    so:

    calendar.monthrange(year, month)[1]
    

    seems like the simplest way to go.

    Just to be clear, monthrange supports leap years as well:

    >>> from calendar import monthrange
    >>> monthrange(2012, 2)
    (2, 29)
    

    My previous answer still works, but is clearly suboptimal.

提交回复
热议问题