3

I have a list of tuples, each containing a date, and then a number.

days = [('04/02/15', 4.5),('03/15/15', 5.0),('04/21/15', 1.9)]

I want to sort them by date. How do I go about converting them into DateTime objects or otherwise sorting them?

MackM
  • 2,906
  • 5
  • 31
  • 45
MikeVaughan
  • 1,441
  • 1
  • 11
  • 18
  • 3
    related http://stackoverflow.com/questions/4183793/str-to-time-in-python, http://stackoverflow.com/questions/466345/converting-string-into-datetime – Nikos M. Apr 24 '15 at 13:52
  • 1
    https://docs.python.org/2/library/time.html#time.strptime – m0dem Apr 24 '15 at 13:52
  • possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – Games Brainiac Apr 24 '15 at 13:54

1 Answers1

6

You could use strptime:

from time import strptime
days = [('04/02/15', 4.5), ('03/15/15', 5.0), ('04/21/15', 1.9)]
days.sort(key = lambda tup: strptime(tup[0], '%m/%d/%y'))
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Thank you, exactly what I needed to do. I will accept the answer as soon as it lets me. – MikeVaughan Apr 24 '15 at 13:58
  • @MikeVaughan: `time.strptime()` returns `time.struct_time`, not `datetime` object as `datetime.strptime()` does and the question title indicates. Though, as a sorting key, `time.struct_time` works here as well. – jfs Apr 27 '15 at 20:50