If you want only one day in the last month, the simplest thing you can do is subtract the number of days from the current date, which will give you the last day of the previous month.
For example, starting from any date:
>>> import datetime >>> today = datetime.date.today() >>> today datetime.date(2016, 5, 24)
Subtracting the days of the current date, we get:
>>> last_day_previous_month = today - datetime.timedelta(days=today.day) >>> last_day_previous_month datetime.date(2016, 4, 30)
This is enough for your simplified need any day in the last month.
But now that you have it, you can also get any day in the month, including the day you started (i.e., more or less the same as subtracting the month):
>>> same_day_last_month = last_day_previous_month.replace(day=today.day) >>> same_day_last_month datetime.date(2016, 4, 24)
Of course, you need to be careful from the 31st to the 30-day month or days absent in February (and take care of leap years), but this is also easy to do:
>>> a_date = datetime.date(2016, 3, 31) >>> last_day_previous_month = a_date - datetime.timedelta(days=a_date.day) >>> a_date_minus_month = ( ... last_day_previous_month.replace(day=a_date.day) ... if a_date.day < last_day_previous_month.day ... else last_day_previous_month ... ) >>> a_date_minus_month datetime.date(2016, 2, 29)
LeoRochael May 24 '16 at 22:14 2016-05-24 22:14
source share