1

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.

2 Answers2

4
from datetime import datetime 
from dateutil.relativedelta import relativedelta 

now = datetime.now()
last_month_date = now + relativedelta(months=-1)
last_month_date=last_month_date.split(" ")[0]

Use dateutil as it has a improved delta

chess_lover_6
  • 632
  • 8
  • 22
  • This isn't the same format as what I need. I need `2021-02-12` and your script is giving me the time as well which I don't need `2021-02-12 17:31:09.836329`. Is there anyway to just have ` 2021-02-12`? –  Mar 13 '21 at 01:33
  • 2
    The default format is ISO down to the fraction of a second. You can modify that with the `.isoformat()` method, but only down to hours, if you want only days then convert it to a date as in `last_month_date.date()`. – John Bayko Mar 13 '21 at 02:17
  • 1
    @JohnBayko thanks for that explaination as that helps me to understand why the format's default is that way. I will mark this in my notes for the future so I can use this. (And trust me I will be using this.) Thanks again John. –  Mar 13 '21 at 02:19
0

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

raspiduino
  • 601
  • 7
  • 16
  • This worked! I had to make the last line a variable like this `lm = last_month_date.strftime('%Y-%m-%d')` then `print(lm)` but that totally worked for me!!! Thank you so much!!!!! –  Mar 13 '21 at 02:13