pythondatetimevariablesformatdatetime

Print date of 1 month ago python


The problem:

I am trying to print out the date from a month ago. So instead of the result being:

>>> 2021-03-12

It will be in this instead

>>> 2021-02-12

Here is my code:

from datetime import date
import datetime
from email.utils import formatdate

now = formatdate(timeval=None, localtime=False, usegmt=True)
tday = date.today()

print(tday)

I have seen tons of different examples but all of them change the format of the date structure that I already have.


Solution

  • Add to @chess_lover_6

    from datetime import datetime 
    from dateutil.relativedelta import relativedelta 
    
    now = datetime.now()
    last_month_date = now + relativedelta(months=-1)
    last_month_date.strftime('%Y-%m-%d')
    

    You will get 2021-02-12