【问题标题】:filtering a list of lists of dates in python在python中过滤日期列表
【发布时间】:2019-04-18 12:16:03
【问题描述】:

我有以下列表:

[[Timestamp('2018-04-07 00:00:00'), Timestamp('2018-07-07 00:00:00'),Timestamp('2020-04-07 00:00:00')], [Timestamp('2018-04-07 00:00:00'),Timestamp('2018-10-07 00:00:00'),Timestamp('2018-12-07 00:00:00'),Timestamp('2021-04-07 00:00:00'),Timestamp('2022-04-07 00:00:00'),Timestamp('2023-04-07 00:00:00')]

我的问题是是否可以按另一个日期过滤列表列表。例如: 如果我选择这个日期:

datetime.datetime(2019, 1, 26, 0, 0)

有没有办法过滤列表列表,只取那些高于我选择的日期以及我的日期之前的最后一个日期的日期? 例如,对于我要保留值的列表的第一个列表:

[Timestamp('2018-07-07 00:00:00'),Timestamp('2020-04-07 00:00:00')]

对于列表列表的第二个列表:

[Timestamp('2018-12-07 00:00:00'),Timestamp('2021-04-07 00:00:00'),Timestamp('2022-04-07 00:00:00'),Timestamp('2023-04-07 00:00:00')]   

【问题讨论】:

    标签: python python-3.x datetime timestamp filtering


    【解决方案1】:

    这样的?

    import datetime
    from pandas import Timestamp
    
    
    # List of Timestamps
    list_of_dates = [[Timestamp('2018-04-07 00:00:00'), Timestamp('2018-07-07 00:00:00'), Timestamp('2020-04-07 00:00:00')], [Timestamp('2018-04-07 00:00:00'), Timestamp('2018-10-07 00:00:00'), Timestamp('2018-12-07 00:00:00'), Timestamp('2021-04-07 00:00:00'), Timestamp('2022-04-07 00:00:00'), Timestamp('2023-04-07 00:00:00')]]
    
    # Target date that we use as filter
    target_date = datetime.datetime(2019, 1, 26, 0, 0)
    
    def filter_dates(date_list, target_date):
      """Filter given timestamps according to target date.
    
      Keep last date before target date and all future dates after target date."""
    
      # Initialise return list
      filtered_dates = []
    
      # Iterate over list of lists
      for dates in date_list:
    
        # Use list comprehension to filter dates that are on either sides of the target date
        dates_before_target_date = [date for date in dates if date < target_date]
        dates_after_target_date = [date for date in dates if date > target_date]
    
        # Keep last date before the target date and all future dates
        filtered_dates.append([dates_before_target_date[-1]] + dates_after_target_date)
    
      return filtered_dates
    
    filtered_dates = filter_dates(list_of_dates, target_date)
    print(filtered_dates)
    

    这会产生

    [
        [Timestamp('2018-07-07 00:00:00'), Timestamp('2020-04-07 00:00:00')],
        [Timestamp('2018-12-07 00:00:00'), Timestamp('2021-04-07 00:00:00'), Timestamp('2022-04-07 00:00:00'), Timestamp('2023-04-07 00:00:00')]
    ]
    

    【讨论】:

      猜你喜欢
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-16
      • 2019-11-20
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多