FinThusiast
FinThusiast

Reputation: 149

Create an object of type datetime64[ns] in python

I have a pandas series like the one below:

import pandas as pd
import numpy as np
s = pd.Series(np.array([20201018, 20201019, 20201020]), index = [0, 1, 2])
s = pd.to_datetime(s, format='%Y%m%d')
print(s)
0   2020-10-18
1   2020-10-19
2   2020-10-20
dtype: datetime64[ns]

I want to check if say the date 2020-10-18 is present in the series. If I do the below I get false.

date = pd.to_datetime(20201018, format='%Y%m%d')
print(date in s)

I guess this is due to the series containing the date in the type datetime64[ns] while the object I created is of type `pandas._libs.tslibs.timestamps.Timestamp'. How can I go about checking if a date is present in such a series?

Upvotes: 2

Views: 1314

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

Actually date in s will check for date in s.index. For example:

0 in s

returns True since s.index is [0,1,2].

For this case, use comparison:

s.eq(date).any()

or, for several dates, use isin:

s.isin([date1, date2]).any()

Upvotes: 3

Related Questions