Search code examples
pythonsortingdatetimelambda

Python: Sort datetime in str format with lambda


I am using sorted(response, key=lambda k: k['createDate'], reverse=False) to get the most recent list members sorted to the front of the list. The problem is that my datetime is in string format %Y-%m-%d %I:%M:%S %p. If I do this sort, it will sort via string comparison and not datetime comparison. How do I work around this issue?

EDIT: Forgot to mention I am usin Python 3.4.


Solution

  • You'll have to parse your values to datetime objects in your key function:

    from datetime import datetime
    
    sorted(
        response,
        key=lambda k: datetime.strptime(k['createDate'], '%Y-%m-%d %I:%M:%S %p'),
        reverse=True,
    )
    

    Had your date format been slightly different, you could have used straight string sorting; ISO8601 dates (formatted to '%Y-%m-%d %H:%M:%S') are lexicographically sortable.

    I also changed the sort order; you want the order reversed, the most recent datetime value will be higher than those that precede it:

    >>> datetime(2014, 6, 11, 17, 16, 10) > datetime(2008, 9, 15, 12, 00, 00)
    True
    

    so the most recent values would be sorted to be the last elements if you don't reverse the sort.