简体   繁体   中英

How to get the date range of the previous month?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM