-1

I have some code that returns the last day of every month in 2017.

Results:

2017-01-31
2017-02-28
2017-03-31
2017-04-30
2017-05-31
2017-06-30
2017-07-31
2017-08-31
2017-09-30
2017-10-31
2017-11-30
2017-12-31

However, I would like to make it include the years 2014 through 2017 and not just 2017. I have not been able to find anything online that would accomplish this and have not been able to figure it out myself. All help/advice would be much appreciated.

Here is my code:

import arcpy
import datetime 
from datetime import timedelta
import time
import calendar

#returns last day of each month
def lastdayofmonth(anyday):
    nextmonth = anyday.replace(day=28) + datetime.timedelta(days=4)
    return next_month - datetime.timedelta(days=nextmonth.day)
for month in range(1, 13):
    print (lastdayofmonth(datetime.date(2017, month, 1)))
Matt A.
  • 123
  • 1
  • 6
  • 2
    possible duplicate of https://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python – Gaur93 Jan 29 '18 at 15:31
  • 4
    Possible duplicate of [Get Last Day of the Month in Python](https://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python) – Mr. T Jan 29 '18 at 15:35
  • 1
    Welcome to SO. Unfortunately this isn't a discussion forum or tutorial. Please take the time to read [ask] and the other links on that page. Invest some time with [the Tutorial](https://docs.python.org/3/tutorial/index.html) practicing the examples. It will give you an idea of the tools Python offers to help you solve your problem. – wwii Jan 29 '18 at 16:47

3 Answers3

0

Simply add a for loop and loop through the years as you did with the months:

for year in range(2014,2018):
    for month in range(1, 13):
        print (lastdayofmonth(datetime.date(year, month, 1)))
ViG
  • 1,848
  • 1
  • 11
  • 13
0

This might be what you want:

import calendar

{(k, m): calendar.monthrange(k, m)[1] for k in range(2014, 2018) for m in range(1, 13)}

# {(2014, 1): 31,
#  (2014, 2): 28,
#  (2014, 3): 31,
#  etc
jpp
  • 159,742
  • 34
  • 281
  • 339
0

As VIG said, you can run second loop to iterator years as your expect range. BTW, I run your code got a error, said next_month no define. you code should fixed as below:

import datetime
from datetime import timedelta
import time
import calendar

#returns last day of each month
def lastdayofmonth(anyday):
    nextmonth = anyday.replace(day=28) + datetime.timedelta(days=4)
    return nextmonth - datetime.timedelta(days=nextmonth.day)


for j in range(2014,2018):

    for month in range(1, 13):
        print (lastdayofmonth(datetime.date(j, month, 1)))
Frank AK
  • 1,705
  • 15
  • 28