Python: How to write to CSV and append date from a DataFrame to the filename -



Python: How to write to CSV and append date from a DataFrame to the filename -

i using next method write csv file date appended filename.

outpath = r'c:\test' filename = "filename_"+(time.strftime("%y%m%d")+".csv") df.to_csv(outpath + "\\" + filename) print outpath + "\\" + filename c:\test\filename_20140621.csv

but have problem when routine crosses midnight , date added incorrect.

i have right date in dataframe df, this:

df['date/time'].head() out[54]: 0 2014-06-20 1 2014-06-20 2 2014-06-20 3 2014-06-20 4 2014-06-20 name: date/time, dtype: object

i utilize date in filename, can't find right way reference it

for example, set date in new dataframe named 'date' 1 column:

date = pd.to_datetime(df['date/time']) date.head() out[15]: 0 2014-06-20 1 2014-06-20 2 2014-06-20 3 2014-06-20 4 2014-06-20 name: date/time, dtype: datetime64[ns]

and tried following:

filename = "filename_"+ date._slice(slice(1))+".csv")

...and various similar things.

can show me how set filename include date dataframe?

any help much appreciated.

give date series, take first, or least, prefer:

>>> date.head() 0 2014-06-20 1 2014-06-20 2 2014-06-20 3 2014-06-20 4 2014-06-20 name: date/time, dtype: datetime64[ns] >>> date.iloc[0].strftime("%y%m%d") '20140620' >>> date.min().strftime("%y%m%d") '20140620'

.iloc[0] accesses first row (regardless of whether index 0, here, or 217123), , .min() scans them , finds smallest. (if know they're same, or 1 want first, .iloc[0] faster .min(), of course, maybe they're not sorted , want smallest.. or largest, max().)

then can create filename easily:

>>> datestr = date.min().strftime("%y%m%d") >>> 'filename_{}.csv'.format(datestr) 'filename_20140620.csv'

python date csv filenames

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -