python date of the previous month

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

    Building off the comment of @J.F. Sebastian, you can chain the replace() function to go back one "month". Since a month is not a constant time period, this solution tries to go back to the same date the previous month, which of course does not work for all months. In such a case, this algorithm defaults to the last day of the prior month.

    from datetime import datetime, timedelta
    
    d = datetime(2012, 3, 31) # A problem date as an example
    
    # last day of last month
    one_month_ago = (d.replace(day=1) - timedelta(days=1))
    try:
        # try to go back to same day last month
        one_month_ago = one_month_ago.replace(day=d.day)
    except ValueError:
        pass
    print("one_month_ago: {0}".format(one_month_ago))
    

    Output:

    one_month_ago: 2012-02-29 00:00:00
    

提交回复
热议问题