Reputation: 151
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.
Upvotes: 1
Views: 1250
Reputation: 98861
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')
Upvotes: 0
Reputation: 1165
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)
Upvotes: 1
Reputation: 402253
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')
Upvotes: 2