0

I am attempting to get the date range of the previous month using Python. For example, today is January 4th, 2021 - I am looking for a way to retrieve "2020-12-01" and "2020-12-31".

I have started with the following:

today = datetime.date.today()
first = today.replace(day=1)
lastMonth = first - datetime.timedelta(days=1)

This gives me the previous month, which I can format like so:

beginningOfMonth = lastMonth.strftime("%Y-%m-01")

However, my attempts to use the calendar module to determine the end of the month/how many days are in the month have failed. Is there an easier way to do this? Preferably without too many package deps...

Thank you in advance

Bobby Bruce
  • 341
  • 5
  • 12

1 Answers1

1

Use calendar.monthrange:

from calendar import monthrange
from datetime import datetime

today = datetime.today()

month = today.month
year = today.year

year = year if today.month != 1 else year - 1 # In case you switch year (Jan -> Dec)

last_month_day = monthrange(year, month)[1] # Number of days of the last month.

With this, you can reformat your strings, since every month starts at 1, and ends at last_month_day

AlanWik
  • 326
  • 1
  • 10
  • 1
    If print last statement - `print(monthrange(year, month))` it will give (2, 31)? What does it mean then? (never mind, i got it) But Maybe you would like to reformat it? – Daniel Hao Jan 04 '21 at 20:33
  • Yes, thanks for pointing it out. Now is corrected. – AlanWik Jan 04 '21 at 20:56