-1

If I use this:

YYYYMMnow = datetime.today().strftime('%Y-%m')

I get as output

2020-11

As of today is November 2020

I want a formula that gives me, YYYY-MM minus one month

it would be an output like

2020-10

or in January, from 2021-01, it would return 2020-12

  • Duplicate [whats-the-simplest-way-to-subtract-a-month-from-a-date-in-python](https://stackoverflow.com/questions/3424899/whats-the-simplest-way-to-subtract-a-month-from-a-date-in-python) – Patrick Artner Nov 13 '20 at 18:18
  • @PatrickArtner significant difference since day-of-month is excluded here – Brad Solomon Nov 13 '20 at 18:19
  • @bradSolomon Thats not a difference - that is a matter of outputting. Plenty of posts for printing dates on SO as well! And he solved the output already: `datetime.today().strftime('%Y-%m')` so the only thing left is subtracting one month wich is handled by the dupe – Patrick Artner Nov 13 '20 at 18:19
  • Does this answer your question? [What's the simplest way to subtract a month from a date in Python?](https://stackoverflow.com/questions/3424899/whats-the-simplest-way-to-subtract-a-month-from-a-date-in-python) – David Buck Nov 13 '20 at 21:34

1 Answers1

1

Logic:

  • Replace the day with 1. Then you don't run into issues such as asking Python "what's one month before March 30"?
  • Subtract 10 days; the day element of the result is irrelevant
  • Truncate to YYYY-MM
from datetime import datetime, timedelta

>>> (datetime.today().replace(day=1) - timedelta(days=10)).strftime('%Y-%m')
'2020-10'
>>> (datetime(year=2020, month=3, day=5).replace(day=1) - timedelta(days=10)).strftime('%Y-%m')
'2020-02'
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235
  • `(datetime(year=2020, month=3, day=5).replace(day=1) - timedelta(days=30)).strftime('%Y-%m')` >> `'2020-01'` I think just subtracting one day, to get the month should be enough instead, if you're just reseting it to the first anyway. – Hampus Larsson Nov 13 '20 at 18:21
  • Ah, good catch @HampusLarsson – Brad Solomon Nov 13 '20 at 18:22