Kode python berikut mengembalikan hari pertama/terakhir bulan sebelumnya tetapi saya ingin dapat mengembalikan hari pertama dari 3 bulan yang lalu sebagai gantinya

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)

OUTPUT SAAT INI

#First day of prev month: 2021-04-01
#Last day of prev month: 2021-04-30
0
Girl007 12 Mei 2021, 13:41

1 menjawab

Jawaban Terbaik

Anda dapat mengonversi bulan ke minggu:

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)

Di luar:

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
1
Maurice Meyer 12 Mei 2021, 11:02