python date of the previous month

前端 未结 12 1360
耶瑟儿~
耶瑟儿~ 2020-11-29 17:05

I am trying to get the date of the previous month with python. Here is what i\'ve tried:

str( time.strftime(\'%Y\') ) + str( int(time.strftime(\'%m\'))-1 )
<         


        
12条回答
  •  独厮守ぢ
    2020-11-29 17:36

    def prev_month(date=datetime.datetime.today()):
        if date.month == 1:
            return date.replace(month=12,year=date.year-1)
        else:
            try:
                return date.replace(month=date.month-1)
            except ValueError:
                return prev_month(date=date.replace(day=date.day-1))
    

提交回复
热议问题