NAGA
NAGA

Reputation: 338

Using current date as file name when exporting dataframe

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.

Upvotes: 4

Views: 12481

Answers (3)

Mohanraj
Mohanraj

Reputation: 83

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)

Upvotes: 0

Filippos Ser
Filippos Ser

Reputation: 386

import datetime
datetime.datetime.now().strftime("%Y-%m-%d")

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81654

You are getting an error because most if not all operating systems don't allow file names to contain /. Use a different separator, such as -:

import time

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

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

Upvotes: 7

Related Questions