Reputation: 2342
I have function in Python Pandas like below (it is sample):
def xyz():
df = pd.DataFrame({"a" : [1,1,1]})
TodaysDate = time.strftime("%Y-%m-%d")
excelfilename = "raport_" +TodaysDate +".xlsx"
df.to_excel(excelfilename, sheet_name="raport", index=True)
return df
Every time I run above function the existing excel file gets overwritten but I need a new excel file to be created every time I run the function. How can I modify my function to do that in Python ?
Upvotes: 0
Views: 992
Reputation: 26
Its because % in your excelfilename becase you are using %X.
Just change:
TodaysDate = time.strftime("%Y-%m-%d %X")
To:
TodaysDate = time.strftime("%Y-%m-%d %H_%M_%S")
I have double checked and its worked on my side :))
For full code:
import pandas as pd
import time
def xyz():
df = pd.DataFrame({"a": [1, 1, 1]})
TodaysDate = time.strftime("%Y-%m-%d %H_%M_%S")
excelfilename = "raport_" + TodaysDate + ".xlsx"
df.to_excel(excelfilename, sheet_name="raport", index=True)
return df
xyz()
Upvotes: 0
Reputation: 218
You should really use ArchAngelPwn's solution in my opinion. Applying random numbers might work but you still run the 1/1000 chance that one file will get overwritten. Also, you might not know which file belongs to which loop/run.
You could also save your file names in a list and check if it exists :
fn = []
def xyz():
df = pd.DataFrame({"a" : [1,1,1]})
TodaysDate = time.strftime("%Y-%m-%d")
excelfilename = "raport_" +TodaysDate +".xlsx"
temp = len(np.where((np.array(fn) == excelfilename)))
fn.append(excelfilename)
df.to_excel("raport_" +TodaysDate + "_" + temp + ".xlsx", sheet_name="raport", index=True)
return df
Upvotes: 0
Reputation: 3046
You can change TodaysDate = time.strftime("%Y-%m-%d")
to TodaysDate = str(time.strftime("%Y-%m-%d %X")).replace(":", "")
or TodaysDate = str(TodaysDate.strftime("%Y-%m-%d %H%M%S"))
This will give you an additional Hour/Minute/Seconds for the creation of your excel. So unless you are running this function multiple times a second this should cover your needs.
Upvotes: 1
Reputation: 454
Maybe something like this. Depends on how many excel files you want to generate.
import random
excelfilename = "raport_" + str(random.randrange(9999)) +TodaysDate +".xlsx"
Upvotes: 1
Reputation: 365
So you can do in this way:
def xyz(itr):
df = pd.DataFrame({"a" : [1,1,1]})
TodaysDate = time.strftime("%Y-%m-%d")
excelfilename = "raport_" +TodaysDate + str(itr) + ".xlsx"
df.to_excel(excelfilename, sheet_name="raport", index=True)
return df
for i in range(9): #or smth another iteration
xyz(i)
Upvotes: 0