I wanted to pull the data for the last month starting from April 1st - April 30 . But additionally also wanted 10 days of data from the previous month (anything after March 21st ) and 3 days from the current month (May 1st - May 3rd) . I have written the below code which will extract the data for April month but was struggling to extract the data for March and May. This is the monthly script so wanted to write a code wherein it will look at the current month and then retrieve the data based on the logic mentioned above in future.
Can someone pls guide me on this?
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')
CodePudding user response:
Used your same calculation to get prev month prev 10 days & current month 3 days
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}')