python date of the previous month

前端 未结 12 1374
耶瑟儿~
耶瑟儿~ 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条回答
  •  萌比男神i
    2020-11-29 17:23

    from datetime import date, timedelta
    
    first_day_of_current_month = date.today().replace(day=1)
    last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)
    
    print "Previous month:", last_day_of_previous_month.month
    

    Or:

    from datetime import date, timedelta
    
    prev = date.today().replace(day=1) - timedelta(days=1)
    print prev.month
    

提交回复
热议问题