python date of the previous month

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

    With the Pendulum very complete library, we have the subtract method (and not "subStract"):

    import pendulum
    today = pendulum.datetime.today()  # 2020, january
    lastmonth = today.subtract(months=1)
    lastmonth.strftime('%Y%m')
    # '201912'
    

    We see that it handles jumping years.

    The reverse equivalent is add.

    https://pendulum.eustace.io/docs/#addition-and-subtraction

提交回复
热议问题