2

This is my first post here so please let me know if I'm doing this wrong...

I'm looking to take the last day of each month for the last 60 months, from a reference date.

For example, if the reference date is today (Aug 21 2014), then the last end of month is July 31st, 2014, and the one before that is June 30th, 2014...

Does anyone know how to do this in python?

Thanks!

ar1994
  • 133
  • 1
  • 9
  • @psicopoo I took a look at that and the question (although similar) isn't the same as what I'm asking... – ar1994 Aug 21 '14 at 16:31

2 Answers2

5

Here's an easier/cleaner way that makes use of the datetime module:

>>> import datetime
>>> def prevMonthEnd(startDate):
...    ''' given a datetime object, return another datetime object that
...        is set to the last day of the prevoius month '''
...    firstOfMonth = startDate.replace(day=1)
...    return firstOfMonth - datetime.timedelta(days=1)
...
>>> theDate = datetime.date.today()
>>> for i in range(60):
...    theDate = prevMonthEnd(theDate)
...    print theDate
...
2014-07-31
2014-06-30
2014-05-31
2014-04-30
2014-03-31
2014-02-28
2014-01-31
2013-12-31
(etc.)
bgporter
  • 35,114
  • 8
  • 59
  • 65
0

Figured it out:

    import calendar

    m = int(raw_input("m: "))
    y = int(raw_input("y: "))

    meArr = []
    monthsleft = 60

    for i in range(1,int(m)):
    meArr = meArr + [str(calendar.monthrange(y,i)[1]) + '.' + str(i) + '.' +         str(y)]
    monthsleft = monthsleft - len(meArr)


    while monthsleft > 0:
        if monthsleft >= 12:
            y = y - 1
            for i in range(12,0,-1):
                meArr = [str(calendar.monthrange(y,i)[1]) + '.' + str(i) + '.' +         str(y)] + meArr
        else:
            y = y - 1
            for i in range(12,m-1,-1):
                meArr = [str(calendar.monthrange(y,i)[1]) + '.' + str(i) + '.' + str(y)] + meArr
        monthsleft = monthsleft - 12
    ##    print(len(meArr))
ar1994
  • 133
  • 1
  • 9