python date of the previous month

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

    You should use dateutil. With that, you can use relativedelta, it's an improved version of timedelta.

    >>> import datetime 
    >>> import dateutil.relativedelta
    >>> now = datetime.datetime.now()
    >>> print now
    2012-03-15 12:33:04.281248
    >>> print now + dateutil.relativedelta.relativedelta(months=-1)
    2012-02-15 12:33:04.281248
    

提交回复
热议问题