Using current date as file name when exporting dataframe

Viewed 8519

I am using Pandas built in to_excel function to create an excel sheet using a data frame I created.

DataSet.to_excel("July24th.xlsx", sheet_name='sheet1', index=False)

I am wondering if I can name my excel sheet using the current date. I want this code to automatically take on the date. I am trying to run my python code on a scheduled basis. so every day I run my code, it will create an excel sheet for that day. I want to keep all the excel sheets generated.

I tried using something like this:

import time
TodaysDate = time.strftime("%d/%m/%Y")
excelfilename = TodaysDate +".xlsx"

DataSet.to_excel(excelfilename, sheet_name='sheet1', index=False).

But the above gives an error. In what other ways can I get such an output.

3 Answers

with following code you can get dynamic filename according to the time you can also add prefix name such as you want. if you need more accurate time as file name you can add fraction also like this cur_time=datetime.now().strftime("%Y-%m-%d-%H:%M-%S.%f").

if you want Abbreviated month name you can use "%b" instead of "%m"

    from datetime import datetime
    
    cur_time=datetime.now().strftime("%Y-%m-%d-%H:%M-%S")
    filename="prefix you need" + cur_time + ".xlsx"
    df.to_excel(filename, sheet_name='sheet1', index=False)
Related