0

I have a function which returns a True or False for specific days. I want to construct a list with all True dates since 2002 using that function.

I have tried:

import datetime as dt

valid_days = []
for year in range(2002,2018):
    for month in range(1,13):
        for day in range(1,32):
            current_date = dt.datetime(year,month,day)
            if(is_valid_day(current_date)):
                valid_days.append(current_date)

However, this implies that for example for February a datetime for day 30 is tried, and I get the following error:

----> 5             current_date = dt.datetime(year,month,day)
ValueError: day is out of range for month

How can this be handled in a pythonic, easy to implement way? The idea would be to just skip date combinations that make no sense (such as February 30th or April 31th). Note: clarity and easy to read code is preferred over performance.

M.E.
  • 4,955
  • 4
  • 49
  • 128
  • 1
    Pick a start date, pick an end date, figure out the difference in days, increment your start date by 1 day until you have reached your end date. See https://stackoverflow.com/a/3240486/4349415 – Mike Scotty Jun 09 '19 at 19:58
  • Possible duplicate of [Creating a range of dates in Python](https://stackoverflow.com/questions/993358/creating-a-range-of-dates-in-python) – Mike Scotty Jun 09 '19 at 20:00
  • I selected the answer from John because it is more related to looping using for, but adding a day until end date is reached as suggested by Mike makes sense – M.E. Jun 09 '19 at 20:04

1 Answers1

1

Use a try/except block to catch the exception.

for day in range(1,32):
    try:
        current_date = dt.datetime(year,month,day)
    except ValueError:
        # once we reach an invalid day, any following
        # days are also invalid, so stop the day loop
        break
    if(is_valid_day(current_date)):
        valid_days.append(current_date)
John Gordon
  • 29,573
  • 7
  • 33
  • 58