Finding array element that matches a certain day

476 Views Asked by At

I have an array of datetime objects

array([datetime.datetime(2009, 8, 1, 0, 0),
   datetime.datetime(2009, 8, 2, 0, 0),
   datetime.datetime(2009, 8, 3, 0, 0),
   datetime.datetime(2009, 8, 4, 0, 0),
   datetime.datetime(2009, 8, 5, 0, 0),
   datetime.datetime(2009, 8, 6, 0, 0),
   datetime.datetime(2009, 8, 7, 0, 0),
   datetime.datetime(2009, 8, 8, 0, 0),
   datetime.datetime(2009, 8, 9, 0, 0),
   datetime.datetime(2009, 8, 10, 0, 0),
   datetime.datetime(2009, 8, 11, 0, 0),
   datetime.datetime(2009, 8, 12, 0, 0),
   datetime.datetime(2009, 8, 13, 0, 0),
   datetime.datetime(2009, 8, 14, 0, 0),
   datetime.datetime(2009, 8, 15, 0, 0),
   datetime.datetime(2009, 8, 16, 0, 0),
   datetime.datetime(2009, 8, 17, 0, 0),
   datetime.datetime(2009, 8, 18, 0, 0),
   datetime.datetime(2009, 8, 19, 0, 0),
   datetime.datetime(2009, 8, 20, 0, 0),
   datetime.datetime(2009, 8, 21, 0, 0),
   datetime.datetime(2009, 8, 22, 0, 0),
   datetime.datetime(2009, 8, 23, 0, 0),
   datetime.datetime(2009, 8, 24, 0, 0),
   datetime.datetime(2009, 8, 25, 0, 0),
   datetime.datetime(2009, 8, 26, 0, 0),
   datetime.datetime(2009, 8, 27, 0, 0),
   datetime.datetime(2009, 8, 28, 0, 0),
   datetime.datetime(2009, 8, 29, 0, 0),
   datetime.datetime(2009, 8, 30, 0, 0),
   datetime.datetime(2009, 8, 31, 0, 0)], dtype=object)

I also have a specific timestamp for an observation

Timestamp('2009-08-01 00:48:00')

I want to find which element in the array is the same day as my timestamp.

I can find the closest time using this:

find_time = np.argmin(np.abs(date_array-this_date))

But that finds the closest time value which can be on a different day (i.e. anything past midday is closer to the next day than it is to midnight on the original day).

How would I just find the element which is the same day (i.e. ignore the sub-day time units and just match on the date).

I can find lots of examples for dealing with datetime arithmetic but these don't seem to work on arrays of datetime objects.

Thanks!

Update: is it this simple?

np.where((data_array == this_date) == True)

1

There are 1 best solutions below

0
On

Use

In [2205]: date_array.astype(np.datetime64) == this_date.date()
Out[2205]:
array([ True, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False], dtype=bool)

Or,

In [2199]: np.array([x.date() for x in date_array]) == this_date.date()
Out[2199]:
array([ True, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False], dtype=bool)