Home > Mobile >  Python - df.to_excel every hour new file
Python - df.to_excel every hour new file

Time:10-13

I am trying to export a dataframe to excel, every hour, with the time of export as filename. So for each export, it should create a new file with a filename of 1 hour later than the previous export.

With my current code, it keeps overwriting one single file, and also not changing to the current time.

My dt_string in combination with the schedule.every is wrong in the first place, since if I print this, it just prints the initial timestamp of when the run started, every x seconds.

import pandas as pd
from datetime import datetime as dt
import schedule
import time

now = dt.now()
dt_string = now.strftime("%Y%m%d %H%M%S")

df = pd.read_excel("file path", sheet_name='data')
def export():
    df.to_excel("file path"   dt_string   ".xlsx", sheet_name='data')

schedule.every(3600).seconds.do(export)

while 1:
    schedule.run_pending()
    time.sleep(1)

CodePudding user response:

You need to move the dt_string initialization into the function

def export():
    now = dt.now()
    dt_string = now.strftime("%Y%m%d %H%M%S")
    df.to_excel("file path"   dt_string   ".xlsx", sheet_name='data')
  • Related