M.E.
M.E.

Reputation: 5495

Handling invalid datetimes

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.

Upvotes: 0

Views: 36

Answers (1)

John Gordon
John Gordon

Reputation: 33335

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)

Upvotes: 1

Related Questions