sorting a list of dicts by a computed field

Larry Martell larry.martell at
Tue Jan 31 15:39:40 EST 2017

On Tue, Jan 31, 2017 at 3:30 PM, Chris Angelico <rosuav at> wrote:
> On Wed, Feb 1, 2017 at 7:26 AM, Larry Martell <larry.martell at> wrote:
>> I have a list of dicts and one item of the dict is a date in m/d/Y
>> format. I want to sort by that. I tried this:
>> sorted(data['trends'], key=lambda k:
>> datetime.strptime(k['date_time'],'%m/%d/%Y'))
>> But that fails with:
>> Exception Type: AttributeError at /report/CDSEM/WaferAlignment/ajax/waChart.json
>> Exception Value: 'module' object has no attribute 'strptime'
>> How can I do this sort?
> I think your problem here may be with how you're trying to parse that
> datetime. There are two common ways to get access to a thing called
> "datetime":
> # Option 1:
> import datetime
> # Option 2:
> from datetime import datetime
> The first one gives you a module; the second gives you just one class
> out of that module (one that happens to have the same name as the
> module itself). My guess is that you're using the first form, but you
> picked up some example code from somewhere that assumes the second.
> Try using "datetime.datetime.strptime" in your key function, and see
> if that helps.

Thanks. I knew that ;-) I've had a very long day, and I don't use
lambda much so I thought it was an issue with that.

More information about the Python-list mailing list