sort dates in python array

后端 未结 9 2060
野的像风
野的像风 2020-11-27 19:39

How to sort the below array of dates on python 2.4

 timestamps = [\'2011-06-2\', \'2011-08-05\', \'2011-02-04\', \'2010-1-14\', \'2010-12-13\', \'2010-1-12\'         


        
相关标签:
9条回答
  • 2020-11-27 20:12

    This sort ascending dates in dd/mm/yyyy format

    from datetime import datetime 
    c_array=['07/12/2017', '30/01/2018', '31/05/2016', '30/09/2016', '30/01/2017', '31/05/2017']
    
    sorted(c_array, key=lambda x: datetime.strptime(x, "%d/%m/%Y").strftime("%Y-%m-%d"))
    #out: ['31/05/2016', '30/09/2016', '30/01/2017', '31/05/2017', '07/12/2017', '30/01/2018']
    
    0 讨论(0)
  • 2020-11-27 20:14
    print(sorted(list_of_strings,key=lambda x :(int(x.split('-')[0]),int(x.split('-')[1]),int(x.split('-')[2])))
    
    0 讨论(0)
  • 2020-11-27 20:17
    >>> import time
    >>> timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']
    >>> timestamps.sort(key=lambda x: time.mktime(time.strptime(x,"%Y-%m-%d")))
    >>> timestamps
    ['2010-1-12', '2010-1-14', '2010-2-07', '2010-2-11', '2010-11-16', '2010-11-22', '2010-11-23', '2010-11-26', '2010-12-02', '2010-12-13', '2011-02-04', '2011-06-2', '2011-08-05', '2011-11-30']
    
    0 讨论(0)
提交回复
热议问题