Pandas dataframe check if date in a column is less than custom days?

Viewed 3412

df has two columns name and date(date in any format - string format/datetime format). Currently its in string format.

df

            name      date              

    0       john     2019-08-24 05:30:30

    1       jude     2020-03-03 21:15:03

if date is less than 10 days from current time, add a new column(output) false to it and true otherwise.

Expected Output

          name      date                 output  

  0       john     2019-08-24 05:30:30    False

  1       jude     2020-03-03 21:15:03    True
1 Answers

Use Series.between with corrent datetime subtracted by 10 days and current datetime:

#if necessary
df['date'] = pd.to_datetime(df['date'])

now = pd.to_datetime('now')
df['output'] = df['date'].between(now - pd.Timedelta(10, 'd'), now)

It working same like chained mask by bitwise AND for greater or equal - Series.ge and less or equal - Series.le:

df['output'] = df['date'].ge(now - pd.Timedelta(10, 'd')) & df['date'].le(now)
#alternative
#df['output'] = (df['date'] >= now - pd.Timedelta(10, 'd')) & (df['date'] <= now)

print (df)
   name                date  output
0  john 2019-08-24 05:30:30   False
1  jude 2020-03-03 21:15:03    True

If want another combinations is possible use Series.lt, Series.gt, Series.le, Series.ge.

If want omit times and working only with dates add Series.dt.date and Timestamp.date:

#if necessary
df['date'] = pd.to_datetime(df['date'])

now = pd.to_datetime('now').date()
df['output'] = df['date'].dt.date.between(now - pd.Timedelta(10, 'd'), now)
print (df)
   name                date  output
0  john 2019-08-24 05:30:30   False
1  jude 2020-03-03 21:15:03    True
Related