how to get first and last dates of past four months in python

Viewed 985

I am trying to get the first and last dates of past four months. I have tried with following concept,

@staticmethod
def getDateRangeByMonth(year, month):
    """

    :param year:
    :param month:
    :return:
    """
    if year is None:
        today = datetime.today()
        year = today.year
    if month is None:
        today = datetime.today()
        month = today.month
    _, num_days = calendar.monthrange(year, month)
    since = datetime.datetime.strptime(str(datetime.date(year, month, 
    1)), "%Y-%m-%d")
    till = datetime.datetime.strptime(str(datetime.date(year, month, 
    num_days)), "%Y-%m-%d")

    return since, till



 for i in range(0,4):
     today = datetime.today()
     since, till = getDateRangeByMonth(today.year, today.month - i)

I know the concept will fall when the past month crosses previous year like if the month is jan or feb then the year have to change.

How to alter this or what am i going wrong with this

thanks in advance

2 Answers
Related