How to get the last day of the month?

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

    In the code below 'get_last_day_of_month(dt)' will give you this, with date in string format like 'YYYY-MM-DD'.

    import datetime
    
    def DateTime( d ):
        return datetime.datetime.strptime( d, '%Y-%m-%d').date()
    
    def RelativeDate( start, num_days ):
        d = DateTime( start )
        return str( d + datetime.timedelta( days = num_days ) )
    
    def get_first_day_of_month( dt ):
        return dt[:-2] + '01'
    
    def get_last_day_of_month( dt ):
        fd = get_first_day_of_month( dt )
        fd_next_month = get_first_day_of_month( RelativeDate( fd, 31 ) )
        return RelativeDate( fd_next_month, -1 )
    

提交回复
热议问题