-2

I have a NumPy array of strings of dates like below. I'm trying to select all dates <'1/31/2020' but I also see the dates that are in February? my code is as below

for date1 in dates[dates <= '2020-01-31']:
    print(date1)

and the data looks like this array of dates

    1/1/2020
    1/2/2020
    1/3/2020
    1/4/2020
    1/5/2020
    2/4/2020
    .
    .
    .
    3/31/2020
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
user3437212
  • 637
  • 1
  • 10
  • 20
  • What is the format of the array? Is `np.datetime64`? See also the [docs](https://docs.scipy.org/doc/numpy/reference/arrays.datetime.html) – Björn Apr 10 '20 at 08:51
  • 2
    Does this answer your question? [Converting string into datetime](https://stackoverflow.com/questions/466345/converting-string-into-datetime) – mkrieger1 Apr 10 '20 at 08:52
  • 1
    Have the dates in the standard ISO format `%Y-%m-%d` so that you can easily do a string compare: `date_array = [datetime.strptime(k, '%m/%d/%Y').strftime('%Y-%m-%d') for k in x]` and `filtered_array = [k for k in date_array if k < '2020-01-31']` – tidakdiinginkan Apr 10 '20 at 08:54

2 Answers2

0

You are actually comparing them as string. As per your Req you can convert them to datetime obj or remove / or - before comparing.

from datetime import datetime as dt
dt.strptime(date, "%m/%d/%y") <= dt.strptime("10/12/13", "%m/%d/%y")
DARK_C0D3R
  • 2,075
  • 16
  • 21
0

You should provide your full code. What do you mean by array? A numpy array, a list, a pandas dataframe? A dict?

To subset dates you will need to convert your date string to a datetime.date object

Björn
  • 1,610
  • 2
  • 17
  • 37