1

I'm trying to sort a list of dates that are in string format but are each in different form, like this:

lst = ['11/04/2016, 23:55', '15/11/2014', '04/05/2016, 23:55', '24/11/2013, 12:30', '31/12/2015']

I've tried the following sorting:

lst.sort(key=lambda date: datetime.strptime(date, "%d/%m/%Y, %H:%M"))

But since I do not know how the dates will be (with the specific hour or without) I got stuck.. I couldn't think of a generic condition to sort this list and I need to keep the exact time if it is given (i.e I don't want to split the string and take only what's before the ,).

Please help :(

user3765713
  • 133
  • 2
  • 13

1 Answers1

2

You can use an if-else statement in your key function:

>>> lst.sort(key=lambda d: datetime.strptime(d, "%d/%m/%Y, %H:%M") if ':' in d else datetime.strptime(d, "%d/%m/%Y"))
>>> lst
['24/11/2013, 12:30', '15/11/2014', '31/12/2015', '11/04/2016, 23:55', '04/05/2016, 23:55']
>>> 

If you might have more that 2 date format you can handle your multiple states in a non in-line function.

def key_func(dat):
    if ':' in dat:
        return datetime.strptime(d, "%d/%m/%Y, %H:%M")
    elif cond2: 
        # return val2
    elif cond3:
        # return val3
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    Thank you very much!! I didn't know you can add a condition into the lambda function, it was just what I needed. Thank you! – user3765713 Apr 24 '16 at 19:10