In python, sorting on date field, field may sometimes be null

后端 未结 2 1370
粉色の甜心
粉色の甜心 2021-02-05 06:00

I am having a hard time coming up with a slick way to handle this sort. I have data coming back from a database read. I want to sort on the accoutingdate. However, accoutingd

2条回答
  •  执笔经年
    2021-02-05 06:12

    Using a key= function is definitely right, you just have to decide how you want to treat the None values -- pick a datetime value that you want to treat as the equivalent of None for sorting purposes. E.g.:

    import datetime
    mindate = datetime.date(datetime.MINYEAR, 1, 1)
    
    def getaccountingdate(x):
      return x['accountingdate'] or mindate
    
    results = sorted(results, key=getaccountingdate, reverse=True)
    

    Just see how much simpler this is than defining a cmp function instead -- and if you do some benchmarking you'll find it's also significantly faster! There's no upside at all in using a cmp function instead of this key function, and it would be a bad design choice to do so.

提交回复
热议问题