Home » excel » python 3.x – Reading in excel file into pandas depending of the month

python 3.x – Reading in excel file into pandas depending of the month

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to read in an Excel file into Pandas.

I am using the following code to get the previous month:

today = datetime.date.today() 
first = today.replace(day=1) 
lastMonth = first - datetime.timedelta(days=1)

Then I go to pull in the file without any errors:

if lastMonth == 12 : pods = pd.ExcelFile(r'\somedrive\PODS data - PODS data - Jan 19.xlsx')
elif lastMonth == 1 : pods = pd.ExcelFile(r'\somedrive\PODS data - Feb 19.xlsx')
else lastMonth == 2 : pods = pd.ExcelFile(r'\somedrive\PODS data - Mar 19.xlsx')

I then attempt to see if it was successfully pulled in by typing pods and I get the following error:

NameError Traceback (most recent call
last) in
—-> 1 pods

NameError: name ‘pods’ is not defined

I’m sure it is something simple, but I can’t quite figure out what it
is

How to&Answers:

As per your question, lastMonth is in date format and if you define that with any number then it might give you error.

I have tried below code that you can try:

import datetime
today = datetime.date.today() 
first = today.replace(day=1) 
lastMonth = first - datetime.timedelta(days=1)
lastMonth.month

if lastMonth.month == 12:
    pods = pd.ExcelFile(r'C:\path\Python\File1.xlsx')
elif lastMonth.month == 1 :
    pods = pd.ExcelFile(r'C:\path\Python\File2.xlsx')
else :
    pods = pd.ExcelFile(r'C:\path\Python\File3.xlsx')

for the last statement(else statement), you do not need to define the condition. let me know if its work for you.