0

以下 python 代码返回上个月的第一天/最后一天,但我希望能够返回 3 个月前的第一天

from datetime import date, timedelta

last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)
start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)
print("First day of prev month:", start_day_of_prev_month)
print("Last day of prev month:", last_day_of_prev_month)

电流输出

#First day of prev month: 2021-04-01
#Last day of prev month: 2021-04-30
4

1 回答 1

1

您可以将几个月转换为几周:

from datetime import date, timedelta


def get_date_range(month_ago):
    weeks = month_ago * 4
    today = date.today()
    last_day_of_prev_month = today.replace(day=1) - timedelta(days=1)
    past_day = last_day_of_prev_month.replace(day=1) - timedelta(weeks=weeks)
    print("First day of prev month:", last_day_of_prev_month)
    print("Last day of prev month:", past_day.replace(day=1))


get_date_range(3)
get_date_range(6)

出去:

First day of prev month: 2021-04-30
Last day of prev month: 2021-01-01

First day of prev month: 2021-04-30
Last day of prev month: 2020-10-01
于 2021-05-12T11:02:46.327 回答