Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get today's date with pandas?

I have a python script that imports a df, processes it, and then outputs to a csv file. I'm using pandas.write_csv() to output the file.

I'm looking to standardize the manner in which my script names the output file. Specifically, I would like for the script to pull today's date as format: MMDDYYYY and insert that to the end of the CSV file.

outputfile = 'mypotentialfilename_MMDDYYYY.csv'
pd.write_csv(outputfile) 

In the past, I've seen quick ways to insert a date into a text, but I cannot seem to find the code to review. Any help is appreciated.

like image 357
ParalysisByAnalysis Avatar asked Oct 04 '17 22:10

ParalysisByAnalysis


2 Answers

python's format can handle date input

today = pd.Timestamp('today')
'filename_{:%m%d%Y}.csv'.format(today)

'filename_10042017.csv'

Using Python 3.6's f-strings

today = pd.Timestamp('today')
f'filename_{today:%m%d%Y}.csv'

'filename_10042017.csv'
like image 165
piRSquared Avatar answered Oct 21 '22 15:10

piRSquared


You could do this with dt.today and dt.strftime:

import datetime as dt

today = dt.datetime.today().strftime('%m%d%Y')  
output_file = 'filename_{}.csv'.format(today)

Also, pd.write_csv is deprecated/removed in newer versions. I suggest upgrading your pandas to the latest version (v0.20 as of now), and using df.to_csv.

like image 32
cs95 Avatar answered Oct 21 '22 16:10

cs95