如果日期早于 24 小时,则从文本文件中删除行

我有一个名为 temp.txt 的文本文件,如果日期早于每天晚上 21:45 之后的 24 小时,我想删除其中的所有行。我已经做了很多谷歌搜索,但在任何地方都找不到答案。文本文件采用以下格式,没有标题:


http://clipsexample1.com,clips1,clipexample123,2019-03-28 17:14:14

http://clipsexample12com,clips2,clipexample234,2019-03-27 18:56:20

如果超过 24 小时,我是否可以删除整行(示例中的第二个剪辑)


编辑:我曾尝试使用此代码,但这只是删除今天的日期,我如何才能删除今天 24 小时?


save_path = 'clips/'

completeName = os.path.join(save_path, 'clips'+str(today)+'.txt')

good_dates = [str(today)]

with open('temp.txt') as oldfile, open(completeName, 'w') as newfile:

    for line in oldfile:

        if any(good_date in line for good_date in good_dates):

            newfile.write(line)


慕神8447489
浏览 113回答 1
1回答

慕桂英4014372

以下csv是我在评论中建议的使用模块的方法:import csvfrom datetime import datetime, timedeltaimport ostoday = datetime.today()cutoff = datetime(year=today.year, month=today.month, day=today.day,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hour=21, minute=45)max_time_diff = timedelta(hours=24)input_file = 'date_temp.txt'save_path = './clips'complete_name = os.path.join(save_path, 'clips'+today.strftime('%Y-%m-%d')+'.txt')os.makedirs(save_path, exist_ok=True)&nbsp; # Make sure dest directory exists.with open(input_file, newline='') as oldfile, \&nbsp; &nbsp; &nbsp;open(complete_name, 'w', newline='') as newfile:&nbsp; &nbsp; reader = csv.reader(oldfile)&nbsp; &nbsp; writer = csv.writer(newfile)&nbsp; &nbsp; next(reader)&nbsp; # Skip header.&nbsp; &nbsp; for line in reader:&nbsp; &nbsp; &nbsp; &nbsp; line_date = datetime.strptime(line[3], "%Y-%m-%d %H:%M:%S")&nbsp; &nbsp; &nbsp; &nbsp; if cutoff - line_date < max_time_diff:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; writer.writerow(line)print('done')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python