Home > Enterprise >  To find a chosen date between date range of two columns
To find a chosen date between date range of two columns

Time:02-18

please help me please to find out the way how to check if "chosen_date" is in range between columns "date1" and "date2".

from datetime import datetime
chosen_date = datetime.today().strftime("%Y-%m-%d")
date1          date2
2000-06-02     2000-06-02
2000-06-03     2000-06-02
2000-06-04     2000-06-02
2000-06-05     2000-06-02
2000-06-06     2000-06-02
2000-06-07     2000-06-02

CodePudding user response:

I imagine you want:

df[(df['date1'] < chosen_date) & (chosen_date < df['date2'])]

However this will always yield nothing in your example as date2 <= date1

CodePudding user response:

As alternative to @mozway's answer you can consider using an extra column and use between.

Data

import pandas as pd
df = pd.DataFrame({"date1":['2000-01-01', '2000-01-10'],
                   "date2":['2000-01-03', '2000-01-11']})

chosen_date = '2000-01-02'

Add chosen_date as column

chosen_date = '2000-01-02'
df["chosen_date"] = chosen_date

Check if chosen_date is in range

df["is_in_range"] = df["chosen_date"].between(df["date1"], df["date2"])
        date1       date2 chosen_date  is_in_range
0  2000-01-01  2000-01-03  2000-01-02         True
1  2000-01-10  2000-01-11  2000-01-02        False
  • Related