Alice Smith
Alice Smith

Reputation: 3

How to save the date and time in the file name in Python?

Hi I realised that my code below will not save multiple files with the same name. I was wondering how I could add the date and time to the .xlsx filename that I generate, so to distinguish several versions of the file.

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt
import xlsxwriter
import os
import time

# Deleting original file
path = (r"C:\Users\M\Downloads\Incident Report.xls")
os.remove(path)
print("Original file has been deleted :)")

excel_file_1 = 'Incident Report.xls'
df_first_shift = pd.read_excel(r'C:\Users\M\3D Objects\New Folder\Incident Report.xls')
print(df_first_shift)

#combining data
df_all = pd.concat([df_first_shift])

# Creating the .xlsx file
timestr = time.strftime("%Y-%m-%d")
print(timestr)
df_all.to_excel(r'C:\Users\M\OneDrive\Test\Incident_Report.xlsx')

Upvotes: 0

Views: 110

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169274

You can use a f-string here:

df_all.to_excel(fr'C:\Users\M\OneDrive\Test\Incident_Report_{timestr}.xlsx')

Upvotes: 2

Related Questions