How to get the last day of the month?

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

    To get the last date of the month we do something like this:

    from datetime import date, timedelta
    import calendar
    last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])
    

    Now to explain what we are doing here we will break it into two parts:

    first is getting the number of days of the current month for which we use monthrange which Blair Conrad has already mentioned his solution:

    calendar.monthrange(date.today().year, date.today().month)[1]
    

    second is getting the last date itself which we do with the help of replace e.g

    >>> date.today()
    datetime.date(2017, 1, 3)
    >>> date.today().replace(day=31)
    datetime.date(2017, 1, 31)
    

    and when we combine them as mentioned on the top we get a dynamic solution.

提交回复
热议问题