如何使用 datetime 模块减少 python 中的日期?

How can i decrement dates in python, by using datetime module?

我有一个日期列表

[datetime.date(2021, 1, 7), datetime.date(2021, 1, 14), datetime.date(2021, 1, 21), datetime.date(2021, 1, 28), datetime.date(2021, 2, 4), datetime.date(2021, 2, 11), datetime.date(2021, 2, 18), datetime.date(2021, 2, 25), datetime.date(2021, 3, 4), datetime.date(2021, 3, 10), datetime.date(2021, 3, 18), datetime.date(2021, 3, 25), datetime.date(2021, 4, 1), datetime.date(2021, 4, 8), datetime.date(2021, 4, 15), datetime.date(2021, 4, 22), datetime.date(2021, 4, 29), datetime.date(2021, 5, 6), datetime.date(2021, 5, 12), datetime.date(2021, 5, 20), datetime.date(2021, 5, 27), datetime.date(2021, 6, 3)]

我想将每个日期至少减少 2 天,例如 -

datetime.date(2021, 1, 7) = datetime.date(2021, 1, 6), datetime.date(2021, 1, 5)

这是我的全部代码 -

before_dates = []
for dates in expiry_list:
    Date = pd.date_range(pd.to_datetime(dates), periods=3).date
    before_dates.append(Date)

此时我使用的是递增日期的代码 -

Date = pd.date_range(pd.to_datetime(dates), periods=3).date

但这段代码只是将日期增加到 3 天 - 示例 -

[array([datetime.date(2021, 1, 7), datetime.date(2021, 1, 8),
        datetime.date(2021, 1, 9)], dtype=object),
 array([datetime.date(2021, 1, 14), datetime.date(2021, 1, 15),
        datetime.date(2021, 1, 16)], dtype=object),
 array([datetime.date(2021, 1, 21), datetime.date(2021, 1, 22),
        datetime.date(2021, 1, 23)], dtype=object),
 array([datetime.date(2021, 1, 28), datetime.date(2021, 1, 29),
        datetime.date(2021, 1, 30)], dtype=object)]

但我想要这种减量格式的输出 - 示例 -

[array([datetime.date(2021, 1, 7), datetime.date(2021, 1, 6),
        datetime.date(2021, 1, 5)], dtype=object),
 array([datetime.date(2021, 1, 14), datetime.date(2021, 1, 13),
        datetime.date(2021, 1, 12)], dtype=object),
 array([datetime.date(2021, 1, 21), datetime.date(2021, 1, 20),
        datetime.date(2021, 1, 19)], dtype=object),
 array([datetime.date(2021, 1, 28), datetime.date(2021, 1, 27),
        datetime.date(2021, 1, 26)], dtype=object)]

所以请帮我解决这个问题。

您可以直接使用List Comprehensions

import datetime

dates = [datetime.date(2021, 1, 7), datetime.date(2021, 1, 14), datetime.date(2021, 1, 21), datetime.date(2021, 1, 28), datetime.date(2021, 2, 4), datetime.date(2021, 2, 11), datetime.date(2021, 2, 18), datetime.date(2021, 2, 25), datetime.date(2021, 3, 4), datetime.date(2021, 3, 10), datetime.date(2021, 3, 18), datetime.date(2021, 3, 25), datetime.date(2021, 4, 1), datetime.date(2021, 4, 8), datetime.date(2021, 4, 15), datetime.date(2021, 4, 22), datetime.date(2021, 4, 29), datetime.date(2021, 5, 6), datetime.date(2021, 5, 12), datetime.date(2021, 5, 20), datetime.date(2021, 5, 27), datetime.date(2021, 6, 3)]


new_dates = [[data - datetime.timedelta(days=i) for i in range(3)] for data in dates]

print(new_dates)