Q:

Lambda syntax error trying to convert to datetime

I was trying to sort a list of dictionaries by the actual datetime, while preserving the value. Something like:
[
    {
        "count": "33",
        "Datetime": "2017-08-22 23:26"
    },
    {
        "count": "35",
        "Datetime": "2017-08-22 23:25"
    },
    {
        "count": "22",
        "Datetime": "2017-08-22 23:27"
    },
]

should be sorted by datetime.
I tried:
def sort_data_by_datetime(data, field_name='Datetime', datetime_format='%Y-%m-%d %H:%M'):

    return sorted(data, key=lambda x: datetime.strptime(x[field_name])

but got syntax error, and ended up with:
def sort_data_by_datetime(data, field_name='Datetime', datetime_format='%Y-%m-%d %H:%M'):

    def convert_datestring_to_datetime(x):
        return datetime.strptime(x[field_name], datetime_format)

    # return sorted(data, key=lambda x: datetime.strptime(x[field_name])
    return sorted(data, key=convert_datestring_to_datetime)

I thought lambdas just had to be a single expression, and the lambda above seems to be a single line. Where is the syntax error with that lambda?

A:

You're missing a closing parens. However, asides that, you also  need to pass the format string to strptime to make it work:
def sort_data_by_datetime(data, field_name='Datetime', datetime_format='%Y-%m-%d %H:%M'):
    return sorted(data, key=lambda x: datetime.strptime(x[field_name], datetime_format))

