python date of the previous month

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

    datetime and the datetime.timedelta classes are your friend.

    1. find today.
    2. use that to find the first day of this month.
    3. use timedelta to backup a single day, to the last day of the previous month.
    4. print the YYYYMM string you're looking for.

    Like this:

     import datetime
     today = datetime.date.today()
     first = today.replace(day=1)
     lastMonth = first - datetime.timedelta(days=1)
     print(lastMonth.strftime("%Y%m"))
    

    201202 is printed.

提交回复
热议问题