0

I am trying to slice today's data from pandas timeseries.

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10000,1),columns=['A'],
                  index=pd.date_range('20140518',periods=10000,freq='T'))

Follwing seems to work fine:

df['2014-05-19']

But when I am using datetime to get today's date by using all the methods below

df[datetime.date.today()]
df[datetime.datetime.now()]
df[datetime.datetime.now().date()]

I get the following Keyerror message

KeyError: datetime.date(2014, 5, 19)

Detailed Error stack is as shown below

C:\Users\<user>\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\series.pyc in __getitem__(self, key)
    489     def __getitem__(self, key):
    490         try:
--> 491             result = self.index.get_value(self, key)
    492             if isinstance(result, np.ndarray):
    493                 return self._constructor(result,index=[key]*len(result)).__finalize__(self)

C:\Users\<user>\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\tseries\index.pyc in get_value(self, series, key)
   1228                 return self.get_value_maybe_box(series, key)
   1229             except (TypeError, ValueError, KeyError):
-> 1230                 raise KeyError(key)
   1231 
   1232     def get_value_maybe_box(self, series, key):

KeyError: datetime.date(2014, 5, 19)
2
  • 3
    Feels hacky, but does df[str(pd.datetime.now().date())] work?
    – DSM
    May 20, 2014 at 1:48
  • 2
    Your datetime slice will result in an exact index call. So something like datetime.datetime.now will try to index something like : 2014-05-19 19:49:54 and datetime.datetime.now().date() will I think get converted to 2014-05-19 00:00:00 by pandas when it attemps the slice. Strings work because they do partial matching.
    – Karl D.
    May 20, 2014 at 1:56

1 Answer 1

1

Try:

df[df.index.date == datetime.date.today()]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.