【问题标题】:python sort dictionary list, of date stringspython排序字​​典列表,日期字符串
【发布时间】:2020-04-30 17:33:38
【问题描述】:

我有一个包含日期和时间字符串的字典列表(来自 JSON)

[{"time": "17:00", "foo": "bar", "date": "01.02.20"}, {"time": "17:00", "foo": "bar", "date": "15.01.20"}, ...

日期格式如下:%d.%m.%y,时间:%H:%M

我当前的代码:

    def sortJSON(self, lis, dateKey, timeKey):
      if timeKey:
        return sorted(lis, key = lambda i: (i[dateKey], i[timeKey]))
      return sorted(lis, key = lambda i: i[dateKey])

但是,由于日期是字符串且格式为 %d.%m.%y,因此它们的排序不正确。 有没有一种优雅的方式可以将我当前的代码与这样的代码结合起来:

Sort list of date strings

换句话说,传入一个附加函数来将值处理为日期?

【问题讨论】:

    标签: python list sorting dictionary lambda


    【解决方案1】:
    def sortIt(key):
        from datetime import datetime
        thelist = [{"date": '30.10.2020'},
                {"date": '30.01.2020'},
                {"date": '30.06.2020'},
                {"date": '17.01.2012'},
                {"date": '25.04.2020'},
                {"date": '03.02.2016'}]
        # Unsorted
        print("-------Unsorted------")
        print(thelist)
        print("-------Sorted------")
        x = sorted(thelist, key = lambda i : datetime.strptime(i.get(key), "%d.%m.%Y"))
        print(x)
    
    sortIt('date')
    

    【讨论】:

      【解决方案2】:

      您可以将日期转换为datetime.datetime 对象进行比较:

      from datetime import datetime
      
      def sortJSON(self, lis, dateKey, timeKey):
          return sorted(lis, key=lambda i: (datetime.strptime(i[dateKey], '%d.%m.%y'), i.get(timeKey)))
      

      【讨论】:

        【解决方案3】:

        您已经很接近了,您需要将string 日期转换为datetime 对象,以便python 可以根据时间比较这些对象,这将起作用:

        from datetime import datetime
        
        d = [{"time": "17:00", "foo": "bar", "date": "01.02.20"}, {"time": "17:00", "foo": "bar", "date": "15.01.20"}]
        
        sorted_dates = sorted(d, key=lambda date: datetime.strptime(date['time'] + ' ' + date['date'], '%H:%M %d.%m.%y'))
        print(sorted_dates)
        
        >>> [{'time': '17:00', 'foo': 'bar', 'date': '15.01.20'}, {'time': '17:00', 'foo': 'bar', 'date': '01.02.20'}]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多