1

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.

naver_news_2018_09_17_10_42.csv
naver_news_2018_09_17_11_42.csv
naver_news_2018_09_17_12_42.csv
naver_news_2018_09_17_13_42.csv 

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

3 Answers 3

2

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank for your help. I works well. I really appreciate your help.
1

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 = datetime.now().strftime(fmt)
    print("%s " % date_stamp)
    return date_stamp


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

Comments

0

According to pandas.DataFrame.to_csv documentation, date_format affects only the Format string for datetime object inside the dataframe, not the filename, but you can use something like:

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

1 Comment

Thanks for your comment. I need to erase it. But do you have any idea to make the filename like "filenave_YYYY_MM_DD_HH_MM.csv"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.