Reputation: 695
I am using the following method to write to a csv file with the date appended to the 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 I have a problem when the routine crosses midnight and the date added is then incorrect.
I have the correct date in a DataFrame df, like 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 would like to use this date in the filename, but I can't find the correct way to reference it
For example, I put this date in a new dataframe named 'date' with just the one 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 the following:
filename = "filename_"+ date._slice(slice(1))+".csv")
...and various similar things.
Can anybody show me how to set the filename to include the date from the DataFrame?
Any help much appreciated.
Upvotes: 2
Views: 14277
Reputation: 61
When using this with pd.ExcelWriter
–this worked:
datestr = tdy.strftime("%Y%m%d")
x = 'FileName_{}.xlsx'.format(datestr)
writer = pd.ExcelWriter(x, engine= "xlsxwriter")
Upvotes: 1
Reputation: 21
Try using the datetime module. Is this what you expect?
import datetime
def _getToday():
return datetime.date.today().strftime("%Y%m%d")
outpath = r'C:\test'
filename = "%s_%s.%s" % ("filename", _getToday() ,".csv")
print outpath + "\\" + filename
Upvotes: 2
Reputation: 353009
Give your date
Series, you could take the first, or the least, as you 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 the first row (regardless of whether its index is 0, as it is here, or 217123), and .min()
scans them all and finds the smallest. (If you know they're all the same, or that the one you want will be first, then .iloc[0]
will be faster than .min()
, of course, but maybe they're not sorted and you want the smallest.. or the largest, with max()
.)
Then you can make a filename easily:
>>> datestr = date.min().strftime("%Y%m%d")
>>> 'filename_{}.csv'.format(datestr)
'filename_20140620.csv'
Upvotes: 4