How to get the last day of the month?

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

    Using dateutil.relativedelta you would get last date of month like this:

    from dateutil.relativedelta import relativedelta
    last_date_of_month = datetime(mydate.year, mydate.month, 1) + relativedelta(months=1, days=-1)
    

    The idea is to get the first day of the month and use relativedelta to go 1 month ahead and 1 day back so you would get the last day of the month you wanted.

提交回复
热议问题