Mary
Mary

Reputation: 1142

comparing date time values in a pandas DataFrame with a specific data_time value and returning the closet one

I have a date column in a pandas DataFrame as follows:

index   date_time
1       2013-01-23
2       2014-01-23
3       2015-8-14
4       2015-10-23
5       2016-10-28

I want to compare the values in date_time column with a specific date, for example date_x = 2015-9-14 ad return a date that is before this date and it is the most closet, which is 2015-8-14.

I thought about converting the values in date_time column to a list and then compare them with the specific date. However, I do not think it is an efficient solution.

Any solution?

Thank you.

Upvotes: 2

Views: 38

Answers (1)

BENY
BENY

Reputation: 323226

Here is one way using searchsorted, and all my method is assuming the data already order , if not doing the df=df.sort_values('date_time')

df.date_time=pd.to_datetime(df.date_time)
date_x = '2015-9-14'
idx=np.searchsorted(df.date_time,pd.to_datetime(date_x))
df.date_time.iloc[idx-1]
Out[408]: 
2   2015-08-14
Name: date_time, dtype: datetime64[ns]

Or we can do

s=df.date_time-pd.to_datetime(date_x)
df.loc[[s[s.dt.days<0].index[-1]]]
Out[417]: 
   index  date_time
2      3 2015-08-14

Upvotes: 2

Related Questions