I have a function which gets the start of the month before the datetime provided:
def get_start_of_previous_month(dt):
'''
Return the datetime corresponding to the start of the month
before the provided datetime.
'''
target_month = (dt.month - 1)
if target_month == 0:
target_month = 12
year_delta = (dt.month - 2) / 12
target_year = dt.year + year_delta
midnight = datetime.time.min
target_date = datetime.date(target_year, target_month, 1)
start_of_target_month = datetime.datetime.combine(target_date, midnight)
return start_of_target_month
However, it seems very convoluted. Can anyone suggest a simpler way? I am using python 2.4.
Use a
timedelta(days=1)
offset of the beginning of this month:.replace(day=1)
returns a new date that is at the start of the current month, after which subtracting a day is going to guarantee that we end up in the month before. Then we pull the same trick again to get the first day of that month.Demo (on Python 2.4 to be sure):