Agustin Gonzalez Ribas
Agustin Gonzalez Ribas

Reputation: 300

How can I match datetime object and Pandas date object?

I am having troubles trying to match a datetime obejct with a Pandas date object.

My code returns this:

IN:

date_ex_dividend = datetime.datetime.strptime(data['ex_dividend'], '%d.%m.%Y')
print (date_ex_dividend,type(date_ex_dividend))

OUT:

2018-01-03 00:00:00 <class 'datetime.datetime'>

IN:

df = pdr.data.DataReader('CIE.MC',start='2018-1-1', end='2018-12-31', data_source = "yahoo")
for index, row in df.iterrows():
    print (index, type(index))

OUT:

2018-01-02 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
2018-01-03 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
2018-01-04 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
2018-01-05 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
2018-01-08 00:00:00 <class 'pandas._libs.tslibs.timestamps.Timestamp'>

As you can see date matches with df in 2nd row: but when I am trying to compare dates, I got this error:

IN:

print (df[date_ex_dividend]==date_ex_dividend)

OUT:

KeyError: datetime.datetime(2018, 1, 3, 0, 0)

Is this because I am trying to campare diferent classes?? Any idea to solve this?

Upvotes: 0

Views: 645

Answers (2)

oli5679
oli5679

Reputation: 1749

You can compare the dataframe you have there with a datetime. The problem is you need to compare your datetime (date_ex_dividend) with then index of your dataframe (df.index).

date_ex_dividend ==df.index

the above creates a mask, you can then use this to find the matching row(s) in the dataframe.

result = df[date_ex_dividend ==df.index]
print(result)

Upvotes: 1

noah
noah

Reputation: 2776

Instead of:

date_ex_dividend = datetime.datetime.strptime(data['ex_dividend'], '%d.%m.%Y')

You should do:

date_ex_dividend = pd.to_datetime(data['ex_dividend'], format='%d.%m.%Y')

This way it will be a proper Pandas datetime object.

Upvotes: 1

Related Questions