How to get the last day of the month?

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

    import calendar
    from time import gmtime, strftime
    calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
    

    Output:

    31
    



    This will print the last day of whatever the current month is. In this example it was 15th May, 2016. So your output may be different, however the output will be as many days that the current month is. Great if you want to check the last day of the month by running a daily cron job.

    So:

    import calendar
    from time import gmtime, strftime
    lastDay = calendar.monthrange(int(strftime("%Y", gmtime())), int(strftime("%m", gmtime())))[1]
    today = strftime("%d", gmtime())
    lastDay == today
    

    Output:

    False
    

    Unless it IS the last day of the month.

提交回复
热议问题