Question

I am sorting a list of dictionaries by date with this code:

try:
    value["spotlight"].sort(key=lambda x: datetime.datetime.strptime(x["start"], "%Y%m%d-%H%M"), reverse=True)
except:
    logger.info("sort exception")
    exc_type, exc_obj, exc_tb = sys.exc_info()
    logger.info(exc_type)
    logger.info(exc_obj)
    logger.info(exc_tb.tb_lineno)

Since February began, I started seeing this exception:

<type 'exceptions.ValueError'> day is out of range for month

How can I tell which dictionary failed so I can debug?

PS - the list is about 500 elements long...

Was it helpful?

Solution

Instead of using a lambda for the key function, write a full function definition. Have this function catch the exception from strptime and raise its own exception with the date string identified.

Using the suggestion from the comments to add information to the existing exception object, with guidance from https://wiki.python.org/moin/HandlingExceptions

def start_key(x):
    d = None
    try:
        d = x["start"]
        return datetime.datetime.strptime(d, "%Y%m%d-%H%M")
    except Exception as e:
        if d:
            e.args += (d,)
        raise

value["spotlight"].sort(key=start_key, reverse=True)

OTHER TIPS

It is certainly a 2013-02-29 or similar.

>>> datetime.datetime.strptime("20130132", "%Y%m%d")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: 2
>>> 
>>> datetime.datetime.strptime("20130229", "%Y%m%d")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 447, in _strptime
    datetime_date(year, 1, 1).toordinal() + 1
ValueError: day is out of range for month
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top