python date of the previous month

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

    Its very easy and simple. Do this

    from dateutil.relativedelta import relativedelta
    from datetime import datetime
    
    today_date = datetime.today()
    print "todays date time: %s" %today_date
    
    one_month_ago = today_date - relativedelta(months=1)
    print "one month ago date time: %s" % one_month_ago
    print "one month ago date: %s" % one_month_ago.date()
    

    Here is the output: $python2.7 main.py

    todays date time: 2016-09-06 02:13:01.937121
    one month ago date time: 2016-08-06 02:13:01.937121
    one month ago date: 2016-08-06
    

提交回复
热议问题