我想從 4 月 1 日到 4 月 30 日提取上個月的資料。但還需要上個月的 10 天資料(3 月 21 日之后的任何資料)和當月 3 天的資料(5 月 1 日至 5 月 3 日)。我撰寫了下面的代碼,它將提取 4 月份的資料,但正在努力提取 3 月和 5 月的資料。這是每月的腳本,所以想撰寫一個代碼,它會查看當前月份,然后根據上面提到的邏輯檢索資料。
有人可以指導我嗎?
import datetime
df["Sent_Date"] = pd.to_datetime(df["Sent_Date"])
from datetime import date, timedelta
#strategy_assignemnt.info()
#Create a last_day_of_the_previous_month variable which will read the system date, then replace it with the day 1 of the current month and set the timedelta which will consider the last month of the last date
last_day_of_the_previous_month = date.today().replace(day = 1)- timedelta(days= 1)
#Create a first_day_of_the_previous_month variable which will read the system date, then replace it with the day 1 of the current month and set the timedelta which will consider the last month of the last date
first_day_of_the_previous_month = date.today().replace(day = 1) - timedelta(last_day_of_the_previous_month.day)
first_day_of_the_previous_month = pd.to_datetime(first_day_of_the_previous_month).strftime ('%Y-%m-%d')
last_day_of_the_previous_month = pd.to_datetime(last_day_of_the_previous_month).strftime ('%Y-%m-%d')
uj5u.com熱心網友回復:
使用相同的計算來獲得上個月前 10 天和當前月 3 天
import datetime
from datetime import date, timedelta
prev_month_last = date.today().replace(day=1) - timedelta(days=1)
prev_month_first = prev_month_last.replace(day=1)
prev_month_prev_10days_start = prev_month_first - timedelta(days=10)
prev_month_prev_10days_end = prev_month_first - timedelta(days=1)
curr_month_3days_start = date.today().replace(day=1)
curr_month_3days_end = curr_month_3days_start timedelta(days=2)
print(f'Previous month start date: {prev_month_first} & end {prev_month_last}')
print(f'Ten days before previous month start date: {prev_month_prev_10days_start} & end {prev_month_prev_10days_end}')
print(f'Current month 3days start {curr_month_3days_start} & end {curr_month_3days_end}')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/475147.html
上一篇:如何使用`as.Date()`將“數字字串”轉換為日期物件?
下一篇:計算時差的快速問題
