4

While i am saving Data Frames in Excel format ("*.xlsx"), i would like to add time stamp to Excel file name.

How can i add run time time stamp to Data Frame while saving in Excel format while saving file using Pandas? Thank you

Felix
  • 1,539
  • 8
  • 20
  • 35

1 Answers1

5

You can use datetime module. It's one of the python standard library, you can access it by pd.datetime like below.

import pandas as pd

writer = pd.ExcelWriter('output_{}.xlsx'.format(pd.datetime.today().strftime('%y%m%d-%H%M%S'))) 
df1.to_excel(writer,'Sheet1')
df2.to_excel(writer,'Sheet2') 
writer.save()

And you can check format code table for the detail.

su79eu7k
  • 7,031
  • 3
  • 34
  • 40
  • Thank you, but for some reason timestamp didn't appear in file name – Felix Apr 07 '16 at 05:40
  • Unfortunately not :-) – Felix Apr 07 '16 at 05:49
  • @Felix What about generated file name? Just 'output_.xlsx'? Please tell me the result of 'pd.datetime.today()' or 'pd.datetime.now()' and 'pd.datetime.today().strftime("%y%m%d-%H%M%S")' on python your consol. – su79eu7k Apr 07 '16 at 06:02
  • pd.datetime.today() Out[6]: datetime.datetime(2016, 4, 6, 23, 4, 53, 50000) pd.datetime.now() Out[7]: datetime.datetime(2016, 4, 6, 23, 5, 24, 216000) pd.datetime.today().strftime("%y%m%d-%H%M%S") Out[8]: '160406-230542' – Felix Apr 07 '16 at 06:06
  • The name is output.xlsx only – Felix Apr 07 '16 at 06:06
  • @Felix Then maybe the code above is not applied correctly. Your file name 'output.xlsx' is old one. As you can see above, it should be 'output_.xlsx'(underbar) at least. It seems that you are using ipython, I recommend check whole code once again and rerun every line(I/O box). – su79eu7k Apr 07 '16 at 06:20
  • The difference is that instead of 'output_{}.xlsx' i am using direct path to server. Might be this is a problem? – Felix Apr 07 '16 at 06:26
  • @Felix Hmm...In my point of view, if the original one(e.g. 'output.xlsx') worked fine, there should be a no problem with that kind of thing. – su79eu7k Apr 07 '16 at 06:36
  • Same issue. File appears just with '_' underbar in name – Felix Apr 07 '16 at 06:44
  • For those who come across this thread, I used `writer = pd.ExcelWriter('output_{}.xlsx'.format(pd.datetime.today().strftime('%Y-%m-%d')), engine='xlsxwriter')` and it worked just fine. – n8-da-gr8 May 02 '19 at 13:59