np_arr = np.array([
[2818, 'Daniel', 'within an hour', '2008-09-24', 4.89, 2.86, 't', 't'],
[5820, 'Sam', 'within an week', '2020-10-24', 4.89, 2.86, 't', 't'],
[5420, 'Franc', 'within an second', '2019-11-24', 4.89, 2.86, 't', 't'],
[5520, 'Sandra', 'within an second', '2019-01-24', 4.89, 2.86, 't', 't']
])
host_since = np_arr[:,3].astype(np.datetime64)
filter = (datetime.now() - host_since.astype('datetime64[M]')).years < 2
filter
How can I get only the dates that are less than two years old? The True/False array should look like this:
array([[False, True, True, False])
CodePudding user response:
Looks like you're defining year as 12 months. Then try:
month_diff = np.array(datetime.now(), 'datetime64[M]') - host_since.astype('datetime64[M]')
mask = month_diff < np.array(24, 'timedelta64[M]')
Output:
array([False, True, True, False])
CodePudding user response:
One approach is to compute the difference in days and find the values that are less than 2 * 365
days:
host_since = np_arr[:, 3].astype(str).astype(np.datetime64)
delta = np.datetime64('today') - host_since
print(delta < np.timedelta64(2 * 365, 'D'))
Output
[False True True False]
CodePudding user response:
The current time, and duration should also be in np.datetime64
format
np.datetime64(datetime.now())
np.timedelta64(2 * 365, 'D')
np_arr = np.array([
[2818, 'Daniel', 'within an hour', '2008-09-24', 4.89, 2.86, 't', 't'],
[5820, 'Sam', 'within an week', '2020-10-24', 4.89, 2.86, 't', 't'],
[5420, 'Franc', 'within an second', '2019-11-24', 4.89, 2.86, 't', 't'],
[5520, 'Sandra', 'within an second', '2019-01-24', 4.89, 2.86, 't', 't']
])
host_since = np_arr[:, 3].astype(np.datetime64)
result = (np.datetime64(datetime.now()) - host_since) < np.timedelta64(2 * 365, 'D')
print(result) # [False True True False]
CodePudding user response:
You can use Python's datetime module:
# Timedelta function demonstration
from datetime import datetime, timedelta
# Using current time
now = datetime.now()
# 730 is two years
twoYearsAgo = now - timedelta(days = 730)
print('2 years ago:', str(twoYearsAgo))
Note: This doesn't account for leap years