Original answer
The following should work: convert your datetimeindex to a series, so you can call apply
and use strftime
to return an array of strings:
In [27]:
import datetime as dt
import pandas as pd
df = pd.DataFrame(index=pd.date_range(start = dt.datetime(2014,1,1), end = dt.datetime.now(), freq='M'))
df.index.to_series().apply(lambda x: dt.datetime.strftime(x, '%b %Y'))
Out[27]:
2014-01-31 Jan 2014
2014-02-28 Feb 2014
2014-03-31 Mar 2014
2014-04-30 Apr 2014
2014-05-31 May 2014
2014-06-30 Jun 2014
2014-07-31 Jul 2014
2014-08-31 Aug 2014
2014-09-30 Sep 2014
2014-10-31 Oct 2014
2014-11-30 Nov 2014
2014-12-31 Dec 2014
2015-01-31 Jan 2015
2015-02-28 Feb 2015
2015-03-31 Mar 2015
2015-04-30 Apr 2015
2015-05-31 May 2015
2015-06-30 Jun 2015
Freq: M, dtype: object
If you want a list then just call tolist()
:
df.index.to_series().apply(lambda x: dt.datetime.strftime(x, '%b %Y')).tolist()
Updated answer
Actually, looking at this question 2 years later, I realise the above is completely unnecessary. You can just do:
In [10]:
df.index.strftime('%Y-%b')
Out[10]:
array(['2014-Jan', '2014-Feb', '2014-Mar', '2014-Apr', '2014-May',
'2014-Jun', '2014-Jul', '2014-Aug', '2014-Sep', '2014-Oct',
'2014-Nov', '2014-Dec', '2015-Jan', '2015-Feb', '2015-Mar',
'2015-Apr', '2015-May', '2015-Jun', '2015-Jul', '2015-Aug',
'2015-Sep', '2015-Oct', '2015-Nov', '2015-Dec', '2016-Jan',
'2016-Feb', '2016-Mar', '2016-Apr', '2016-May', '2016-Jun',
'2016-Jul', '2016-Aug', '2016-Sep', '2016-Oct', '2016-Nov',
'2016-Dec', '2017-Jan', '2017-Feb', '2017-Mar', '2017-Apr',
'2017-May', '2017-Jun', '2017-Jul'],
dtype='<U8')
datetimeindex
support .dt
accessors directly without converting to a Series
.loc[]
When you say "in order to use them to plot", I suspect you want the actual datetimes to make the slice with.loc[]
, not just the string labels for the plot's time-axis. – Russon