I have calculated the difference between a date in my pd df and and the date now. I need to write a function that checks if these dates are more than three years apart, and if so, 'block' a contact in by asking confirmation to the user that they want this contact blocked.
#calculate time difference and determine today's date
df_transactions['month'] = df_transactions['date'].str.split('/').str[1]
month = df_transactions['month']
time_difference = (pd.Timestamp.now().normalize() - pd.to_datetime(df_transactions['date'], errors='coerce'))
three_years = pd.to_datetime('2019-1-01')
#function: compare todays date with date from df and ask to block user
def date_block():
if time_difference > three_years:
if df_transactions["access"].any() == True:
print(df_transactions["sender"] " " '')
input('Would you like to restrict this contact? ')
# block_contact(select_transaction['sender'])
else:
print('else statement triggered')
date_block()
The error I'm getting is the following:
pandas.core.arrays.datetimelike.InvalidComparison: 2019-01-01 00:00:00
How do I compare the two dates in a way that will not give me an error?
Thanks!
CodePudding user response:
The problem might be that you compare timedelta
with datetime
which does not work. Try the following:
date_range = pd.date_range(start='2018-01-01', end='2022-06-01')
df = pd.DataFrame(date_range, columns=['date'])
df['time_diff'] = (pd.Timestamp.now() - pd.to_datetime(date_range))
df['>3 years'] = df['time_diff']/pd.Timedelta(days=365) > 3
Output:
date time_diff >3 years
0 2018-01-01 1613 days 09:38:59.903248 True
1 2018-01-02 1612 days 09:38:59.903248 True
2 2018-01-03 1611 days 09:38:59.903248 True
3 2018-01-04 1610 days 09:38:59.903248 True
4 2018-01-05 1609 days 09:38:59.903248 True
... ... ... ...
1608 2022-05-28 5 days 09:38:59.903248 False
1609 2022-05-29 4 days 09:38:59.903248 False
1610 2022-05-30 3 days 09:38:59.903248 False
1611 2022-05-31 2 days 09:38:59.903248 False
1612 2022-06-01 1 days 09:38:59.903248 False
CodePudding user response:
I think firstly, you should use your date as int and substract them and convert the result in date then compare it