Skip to main content
 首页 » 编程设计

python之在 python 中过滤日期列表的列表

2024年12月31日8insus

我有以下列表:

[[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')]    

请您参考如下方法:

是这样的吗?

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')] 
]