python date of the previous month

前端 未结 12 1395
耶瑟儿~
耶瑟儿~ 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:25

    For someone who got here and looking to get both the first and last day of the previous month:

    from datetime import date, timedelta
    
    last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)
    
    start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)
    
    # For printing results
    print("First day of prev month:", start_day_of_prev_month)
    print("Last day of prev month:", last_day_of_prev_month)
    

    Output:

    First day of prev month: 2019-02-01
    Last day of prev month: 2019-02-28
    

提交回复
热议问题