Reputation: 35
Good evening,
I need to display which dates are between today and a given date in the past. Here is the code.
import pandas as pd
from datetime import datetime,timedelta
df = pd.DataFrame({'DateOFBirth': ['28/03/2020','2/03/2020','12/02/2021']})
df['DateOFBirth'] = pd.to_datetime(df['DateOFBirth'],format='%d/%m/%Y')
print(df.dtypes)
print(df)
x = input ("No of days: ")
today = datetime.date(datetime.now())
result = today - timedelta(days=int(x))
#np.datetime(result).astype(datetime64)
print(result < df['DateOFBirth'] < today)
I tried to cast date to datetime64[ns] and the other way around but I had no luck. Any solution to make the last print() statement work? Thank you!
Sample output: If today is 28.03.2020 and x is set to 30 days the output should be:
28/03/2020
2/03/2020
Upvotes: 0
Views: 2413
Reputation: 1249
You can compute today
with pd.to_datetime()
too, to have the same date format :
today = pd.to_datetime(datetime.now())
An other error may occur because you are comparing an entire column with a single number:
print(result < df['DateOFBirth'] < today)
You can compute the output you want with this line instead:
mask = (df['DateOFBirth'] > result) & (df['DateOFBirth'] <= today)
print(df.loc[mask])
The result will be:
DateOFBirth
0 2020-03-28
1 2020-03-02
Upvotes: 0
Reputation: 3528
You can use between too
import pandas as pd
from datetime import datetime,timedelta
df = pd.DataFrame({'DateOFBirth': ['28/03/2020','2/03/2020','12/02/2021']})
df['DateOFBirth'] = pd.to_datetime(df['DateOFBirth'],format='%d/%m/%Y')
x = input ("No of days: ")
today = pd.to_datetime(datetime.now())
result = today - timedelta(days=int(x))
bw_values = df[df['DateOFBirth'].between(result, today, inclusive=False)]
# output if x = 30
print(bw_values)
DateOFBirth
0 2020-03-28
1 2020-03-02
Or You can also use Query
bw_values = df.query('@result < DateOFBirth < @today')
Upvotes: 2