MaartenJ
MaartenJ

Reputation: 13

How to sort a list of string dates

I need some help with sorting a list of dates. I have a few lines of code and I tried a lot of different solutions I found on the internet but none of them seems to work.

import datetime

class WhiteChocolate:
    def __init__(self, vervaldatum):
        self.vervaldatum = vervaldatum


WhiteChocoStock = []

WhiteChocoStock.append(WhiteChocolate("22/04/2014"))
WhiteChocoStock.append(WhiteChocolate("21/04/2015"))
WhiteChocoStock.append(WhiteChocolate("12/12/2013"))

test = sorted(WhiteChocoStock, key=lambda x: datetime.datetime.strptime(x, '%d/%m/%Y'))

I don't know what I'm doing wrong.

Upvotes: 0

Views: 358

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You are trying to sort a list of objects, when you need to sort by the vervaldatum property of each of the objects in your list, which contains the date string:

sorted(WhiteChocoStock, key=lambda x: datetime.datetime.strptime(x.vervaldatum, '%d/%m/%Y'))

Upvotes: 1

Related Questions