python pandas to csv file save, not override

1357 views python

I read a csv file and did some modification of the data repeatedly. And I tried to save the csv with the file name "naver_news_YYYY_MM_DD_HH_MM.csv. However, If I run this program repeatedly, but I can find only last csv file with "naver_news.csv".

This is the code as followed.

df.to_csv("C:/Users/Administrator/PycharmProjects/news/naver_news.csv", date_format='%Y-%m-%d', index = False, sep=',', encoding='ms949')

Then I can only find one "naver_news.csv" file in my computer. The result file nave that I am expecting is as followed.


Please let me know to save csv file with current current time.

answered question

3 Answers


You'll need to insert the timestamp label into the filename yourself.

ts = pd.to_datetime('today').strftime('%Y_%m_%d_%H_%M')
filename = f"C:/Users/Administrator/PycharmProjects/news/naver_news_{ts}.csv"
# filename = "C:/Users/Administrator/PycharmProjects/news/naver_news_{}.csv".format(ts) 
df.to_csv(filename, index=False, encoding='ms949')

posted this

According to pandas.DataFrame.to_csv documentation, date_format affects only the Format string for datetime object inside the dataframe, not the filename.

You can use datetime and format to achieve what you need, i.e.:

from datetime import datetime
fn = "C:/Users/Administrator/PycharmProjects/news/naver_news_{}.csv".format(format(, '%Y_%m_%d_%H_%M'))
df.to_csv(fn, index = False, sep=',', encoding='ms949')

posted this

You can create a function to get timestamp whenever you want,

from datetime import datetime

def get_date_time(fmt='%Y_%m_%d_%H_%M_%S'):
    date_stamp =
    print("%s " % date_stamp)
    return date_stamp

file_name = "C:/Users/Administrator/PycharmProjects/news/naver_news_{}.csv".format(get_date_time())

posted this

Have an answer?


Please login first before posting an answer.