To accomplish the task you described, we will follow these steps:
- Read the Excel file.
- Identify the date column and filter out the data to get the last 13 full days (excluding the partial day at the time of download).
- Save the filtered data to a new Excel file.
We will use the pandas library for data manipulation and datetime/dateutil for handling dates.
First, ensure you have the necessary libraries installed:
pip install pandas openpyxl python-dateutil
Here's a Python script that accomplishes the task:
import pandas as pd
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta, MO, TU, WE, TH, FR
def is_weekday(date):
"""Check if a date is a weekday."""
return date.weekday() < 5
def get_last_n_business_days(date, n):
"""Get the last n business days (excluding the given date)."""
business_days = []
current_date = date - relativedelta(days=1) # Start from the previous day
while len(business_days) < n:
if is_weekday(current_date):
business_days.append(current_date)
current_date -= relativedelta(days=1)
return business_days
def filter_data(df, date_column):
"""Filter the DataFrame to include data for the last 13 full business days."""
# Assuming the date_column is of datetime type
max_date = df[date_column].max().date() # Get the max date in the data
last_13_business_days = get_last_n_business_days(max_date, 13)
# Filter the data
filtered_df = df[df[date_column].dt.date.isin(last_13_business_days)]
return filtered_df
def main(file_path, date_column):
"""Main function to read Excel, filter data, and save to a new Excel file."""
try:
# Read the Excel file
df = pd.read_excel(file_path)
# Ensure the date column is of datetime type
df[date_column] = pd.to_datetime(df[date_column])
# Filter the data
filtered_df = filter_data(df, date_column)
# Create a new Excel file name
new_file_name = f"filtered_data_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
# Save the filtered data to a new Excel file
filtered_df.to_excel(new_file_name, index=False)
print(f"Data successfully saved to {new_file_name}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
file_path = "your_file.xlsx" # Path to your Excel file
date_column = "date" # Name of the column containing dates
main(file_path, date_column)
How to Use:
- Replace
"your_file.xlsx" with the path to your Excel file.
- Replace
"date" with the name of the column in your Excel file that contains the dates.
This script reads an Excel file, filters the data to include only the rows where the date falls within the last 13 full business days (excluding the day of download), and saves the filtered data to a new Excel file. The script accounts for weekends and can be adapted for holidays by modifying the is_weekday function or adding additional logic to skip holidays.