首页 > 解决方案 > 如何根据日期时间过滤文件?

问题描述

我有一个文件,如果它们满足 2 个条件,我想将一些行附加到一个空列表中:

  1. 我只取那些country_code也存在于my_countrycodesAND中的行
  2. country_code如果日期时间为<my_time1

请注意,country_code每行的索引在[1]文件中,每行的日期时间是一个名为 的变量date_time4

这是我的代码:

my_time = '2020-09-06 16:00:45'
my_time1 =  datetime.datetime.strptime(my_time, '%Y-%m-%d %H:%M:%S') 

my_countrycodes = ['555', '256', '1000']

all_row_times = [] #<--- this is the list where we will append the datetime values of the file
new_list = [] #<--- this is the final list where we will append our results
    
with open(root, 'r') as out:
    reader = csv.reader(out, delimiter = '\t')
    for row in reader:  
        # print(row)
        date_time1 = row[-2] + row[-1] #<--- concatenate date + time
        date_time2 = datetime.datetime.strptime(date_time1, '%d-%m-%Y%H:%M:%S') #<--- make a datetime object of the string
        date_time3 = datetime.datetime.strftime(date_time2, '%Y-%m-%d %H:%M:%S') #<--- turn the datetime object  back to a string
        date_time4 = datetime.datetime.strptime(date_time3, '%Y-%m-%d %H:%M:%S') #<--- turn the string object  back to a datetime object
        all_row_times.append(date_time4) #<--- put all the datetime objects into a list.
        
        if any(country_code in row[1] for country_code in my_countrycodes) and date_time4 == max(dt for dt in all_row_times if dt <  my_time1): 
            new_list.append(row) #<-- append the rows with the same country_code in my_countrycodes and the latest time if that time is < my_time1
                
print(new_list)

这是文件的样子: 在此处输入图像描述

这是的输出new_list

[['USA', '555', 'White', 'True', 'NY', '06-09-2020', '10:11:32'], 
['USA', '555', 'White', 'True', 'BS', '06-09-2020', '10:11:32'], 
['EU', '256', 'Blue', 'False', 'BR', '06-09-2020', '11:26:21'], 
['GE', '1000', 'Green', 'True', 'BE', '06-09-2020', '14:51:45'], 
['GE', '1000', 'Green', 'True', 'BE', '06-09-2020', '15:59:45']]

如您所见,代码提取带有country_codes 555,2561000的行,它还提取小于 < 的行my_time1。所以这部分工作完美。但是,行1000有 2 个不同的日期时间,我不明白为什么它不只占用 MAX 日期时间。

这是预期的输出new_list

[['USA', '555', 'White', 'True', 'NY', '06-09-2020', '10:11:32'], 
['USA', '555', 'White', 'True', 'BS', '06-09-2020', '10:11:32'], 
['EU', '256', 'Blue', 'False', 'BR', '06-09-2020', '11:26:21'],  
['GE', '1000', 'Green', 'True', 'BE', '06-09-2020', '15:59:45']]

标签: pythonlistfiledatetime

解决方案


实际上,它只需要 MAX 日期时间,但在 for 循环中,14:51:45首先出现。您的代码将其与其他代码进行比较,由于尚未出现其他值,因此将其作为最大值。

在下一次迭代中,另一个国家代码出现了,因为它的时间比其他代码大,所以也附加了这一行。我猜这就是你所缺少的。

你可以试试这样的。

my_time =  datetime.datetime.strptime('2020-09-06 16:00:45', '%Y-%m-%d %H:%M:%S')
my_countrycodes = ['555', '256', '1000']

country_code_max_date_rel = {}
matched_rows = []
with open(root, 'r') as out:
    reader = csv.reader(out, delimiter = '\t')
    for row in reader:
        date_time = datetime.datetime.strptime(row[-2] + row[-1], '%d-%m-%Y%H:%M:%S')
        if any(country_code in row[1] for country_code in my_countrycodes):
            matched_rows.append(row)
            try:
                if country_code_max_date_rel[str(row[1])] < date_time:
                    raise KeyError
            except KeyError:
                country_code_max_date_rel[str(row[1])] = date_time

此时,您拥有每个国家/地区的最大值。还有行列表。如果你再次过滤喜欢;

new_list = []
for row in matched_rows:
    country_code = row[1]
    date_time = datetime.datetime.strptime(row[-2] + row[-1], '%d-%m-%Y%H:%M:%S')
    if date_time == country_code_max_date_rel[country_code]:
        if date_time < my_time:
            new_list.append(row)

新名单:

[['USA', '555', 'White', 'True', 'NY', '06-09-2020', '10:11:32'],
 ['USA', '555', 'White', 'True', 'BS', '06-09-2020', '10:11:32'],
 ['EU', '256', 'Blue', 'False', 'BR', '06-09-2020', '11:26:21'],
 ['GE', '1000', 'Green', 'True', 'BE', '06-09-2020', '15:59:45']]

这段代码不是很好,但我想它会帮助你更新你的。


推荐阅读