How to get the last day of the month?

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

    The simplest way is to use datetime and some date math, e.g. subtract a day from the first day of the next month:

    import datetime
    
    def last_day_of_month(d: datetime.date) -> datetime.date:
        return (
            datetime.date(d.year + d.month//12, d.month % 12 + 1, 1) -
            datetime.timedelta(days=1)
        )
    

    Alternatively, you could use calendar.monthrange() to get the number of days in a month (taking leap years into account) and update the date accordingly:

    import calendar, datetime
    
    def last_day_of_month(d: datetime.date) -> datetime.date:
        return d.replace(day=calendar.monthrange(d.year, d.month)[1])
    

    A quick benchmark shows that the first version is noticeably faster:

    In [14]: today = datetime.date.today()
    
    In [15]: %timeit last_day_of_month_dt(today)
    918 ns ± 3.54 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    In [16]: %timeit last_day_of_month_calendar(today)
    1.4 µs ± 17.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    

提交回复
热议问题