rob zaenglein
rob zaenglein

Reputation: 55

How to fetch timestamp in Pandas DataFrame

I'm trying to plot pandas to the web using Flask. I think i'm on the right track but i'm struggling to grab the date to put on the x axis.

for the y axis data, its easy:

aapl = pd.io.data.get_data_yahoo('AAPL', start=datetime.datetime(2006, 10, 1), end=datetime.datetime(2012, 1, 1))     
all_close = appl['Close'][10:]
for close in all_close:
    y.append(close)

easy enough. However there seems to be no way to get to the date out of the object this returns

This is what the dataframe looks like:

            Open   High    Low  Close    Volume  Adj Close
Date                                                       
2006-10-02  75.10  75.87  74.30  74.86  25451400      72.38
2006-10-03  74.45  74.95  73.19  74.08  28239600      71.63
2006-10-04  74.10  75.46  73.16  75.38  29610100      72.89
2006-10-05  74.53  76.16  74.13  74.83  24424400      72.35
2006-10-06  74.42  75.04  73.81  74.22  16677100      71.76

Anyone know how i'd get to that date?

Thanks

Upvotes: 2

Views: 339

Answers (1)

Nipun Batra
Nipun Batra

Reputation: 11367

Date is the index of your DataFrame. You can access it simply as follows:

df.index

Vanilla example

In [13]: index = pd.DatetimeIndex(start='2012', end='2013', freq='1D')

In [14]: index
Out[14]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-17 00:00:00, ..., 2013-01-17 00:00:00]
Length: 367, Freq: D, Timezone: None


In [15]: df = pd.DataFrame(np.random.randn(len(index),1), index=index)

In [16]: df
Out[16]: 
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 367 entries, 2012-01-17 00:00:00 to 2013-01-17 00:00:00
Freq: D
Data columns (total 1 columns):
0    367  non-null values
dtypes: float64(1)

In [17]: df.index
Out[17]: 
<class 'pandas.tseries.index.DatetimeIndex'>
[2012-01-17 00:00:00, ..., 2013-01-17 00:00:00]
Length: 367, Freq: D, Timezone: None

This works for other types of indices as well.

In case you are looking for DatetimeIndex specific, you may find more details about timeseries here.

Upvotes: 1

Related Questions