【问题标题】:Delete in lines in file with that older then 90 days in python在 python 中删除超过 90 天的文件中的行
【发布时间】:2022-01-24 16:39:30
【问题描述】:

我有一个包含日期的文件,我想删除所有超过 90 天的日期。 示例:

2020-02-26
2009-03-21
2021-04-12
2021-01-21

我想不出办法。

到目前为止,我能做的是仅从文件中提取日期并将其打印为列表:

file = open('dates_file', 'r')
Lines = file.readlines()

count = 0
# Strips the newline character
for line in Lines:
    count += 1
    #print(line.strip())
    index = 10
    if len(line) > index:
        line = line[0: index :]
        print(line.strip())

编辑:

我已经编辑了脚本并且能够从 90 天前提取日期以将其与文件中的日期进行比较,并且我能够获得我需要删除的所有日期的输出。

这是目前为止的脚本:

past = datetime.now().date() - timedelta(days=90)
present = datetime.now()
index = 10

file = open('dates_file', 'r')
Lines = file.readlines()


count = 0
# Strips the newline character
for line in Lines:
    count += 1
    if len(line) > index:
        line = line[0: index :]
    if line.strip() < str(past):
        print(line.strip())

【问题讨论】:

  • 这能回答你的问题吗? How to compare two dates?
  • 一旦你读到一行,从该字符串中提取数据并将其转换为 datetime 对象,一旦完成,你就可以轻松检查那里的天数差异
  • @wjandrea 很遗憾没有,我检查了一下它似乎没有做我需要的事情
  • @Daniel 以什么方式?如果这就是您所指的,它不会删除行,但这是一个单独的问题。如果你也需要帮助,试试这个问题:How to delete a specific line in a file?
  • @wjandrea,它对我没有帮助,因为出现在我面前的日期是这样的: 2021-09-24 21:12:57.488002 我需要的是 2021-09-24 。当我尝试打印 len 以使其与我的格式匹配但它给了我一个错误: TypeError: object of type 'datetime.datetime' has no len() 关于如何删除文件,我知道如何,我只需要了解获取早于 90 天的日期。编辑,nvm 我是个白痴,我找到了一种只获取日期的方法 datetime.now().date() 现在你认为删除日期会更好吗?

标签: python python-3.x


【解决方案1】:

您文件中的日期是 ISO 格式,其优点是可以在词法上比较该样式的日期。因此你可以这样做:

from datetime import datetime, timedelta, date
# calculate and format a date that is 90 days prior to the current date
prev = date.strftime(datetime.today() - timedelta(days=90), '%Y-%m-%d')

with open('dates_file', 'r+') as dates:
    # build a list of dates that are greater than *prev*
    d = [s for s in dates if s.strip() > prev]
    dates.seek(0) # seek to start of file
    dates.write(''.join(d)) # write the list
    dates.truncate() # truncate

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2021-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-20
相关资源
最近更新 更多