【问题标题】:Calculating the previous date by one, two, or three days按一、二或三天计算前一个日期
【发布时间】:2018-12-01 15:10:25
【问题描述】:

我正在按一、二或三天计算前一个日期。我有一个执行此操作的函数,但我希望能够根据存在的先前 JSON 文件计算正确的先前日期。

我知道我需要某种条件语句,但我不确定如何处理。然后,该变量将在 for 循环中用于读取前一天文件和当天文件的内容,以进行一些分析。如果前一天的文件不可用,则需要将其加一,直到找到文件。

我的代码如下:

def previous_day():
    previous_day = str(datetime.date.today() - datetime.timedelta(1))
    return str(previous_day)


def current_day():
    current_day = str(datetime.datetime.today().strftime('%Y-%m-%d'))
    return str(current_day)


with open(currentday + '.json', 'r') as f, open(previousday + '.json', 'r') as g:
    for cd, pd in zip(f, g):
        data_current = json.loads(cd)
        data_previous = json.loads(pd)

【问题讨论】:

  • 会有today文件吗?你是说你想打开最新的文件和下一个当前文件——相对于today?请举几个你正在处理的文件名的例子......minimal reproducible example
  • 基本上,对于当前日期,它将是最新的文件。我已经介绍过。它正在计算上一个文件。例如,可能没有 2018-12-02 的文件,因此它会尝试查找下一个文件 2018-12-01 等 @wwii

标签: python python-3.x python-2.7 date datetime


【解决方案1】:

如果您只是想查找最近的 2 个文件进行比较,我认为您根本不需要担心日期计算,因为您的文件名只是 ISO 日期字符串。您可以获取目录中的所有文件,对它们进行排序,然后按您想要的任何顺序进行比较。

从目录中获取所有文件名

import os

files = os.listdir('/home/foo/bar')
# if there are unneeded files or subdirectories, filter the resulting list

按日期降序对文件进行排序

files = ['2018-11-23.json', '2018-11-29.json', '2018-11-25.json']
files.sort(key=lambda f: f.split('.')[0], reverse=True)
# sort output: ['2018-11-29.json', '2018-11-25.json', '2018-11-23.json']

打开最近和下一个最近的文件进行比较

with open(files[0], 'r') as latest, open(files[1], 'r') as previous:
    # compare files
    pass

【讨论】:

  • 这样做很有意义。但是,在这个例子@benvc 中是否必须使用 lambda 函数?
  • @arousayasser - 您不必使用 lamda 作为键功能,您可以编写/定义常规功能并使用它。如果提取要排序的值复杂regular 函数比 lambda 更具可读性。
  • 我收到错误消息:ile "json_compare.py", line 40, in main with open(files[0], 'r') as f, open(files[1], 'r ') as g: IOError: [Errno 2] No such file or directory: '2018-12-01.json' 我没有创建带有硬编码名称的文件列表。我希望能够将其存储到列表中。 @benvc
  • @arousayasser - 您可能需要在 with open(...) 语句中的文件名开头附加一个路径,具体取决于您运行脚本的位置。
猜你喜欢
  • 1970-01-01
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多