-3

So I have the following list of dates

list_dates=[np.datetime64('2018-06-11'),np.datetime64('2018-01-01'),
np.datetime64('2018-03-02'),np.datetime64('2018-03-11'),
np.datetime64('2018-05-19'),np.datetime64('2017-03-19'),
np.datetime64('2018-01-01'),np.datetime64('2017-05-30'),
np.datetime64('2016-08-11'),np.datetime64('2016-06-04')]

I would like to generate a new list only with those dates with the months of january and march.

The desired output would look something like this:

[np.datetime64('2018-01-01'),np.datetime64('2018-03-02'),np.datetime64('2017-03-19'),
np.datetime64('2016-03-11')]

I was thinking I was treating with strings so I did this

 dates_selected=[x for x in list_dates if "-03-" in x ]+
                [x for x in list_dates if "-01-" in x ]

The problem is that I recieved an ouput indicating that:

TypeError: arguments of type numpy.datetime64 is not iterable

How could I obtain the desired ouput considering I am treating with datetime64 instead of strings?

JamesHudson81
  • 2,215
  • 4
  • 23
  • 42
  • They are strings. Nowhere in your examples are they anything other than strings; not `datetime` objects or `numpy.datetime64` objects – roganjosh Jun 04 '19 at 22:48
  • You *are* are treating with strings; the code you posted works just as you wish, albeit with the March dates first, since that's what you specified in your comprehensions. – Prune Jun 04 '19 at 22:49
  • Can you specify the output you are getting, and what you expected instead – Hari Menon Jun 04 '19 at 22:50
  • 3
    Your edit has thrown the whole question into the no- [mcve] realm – roganjosh Jun 04 '19 at 22:52
  • Are you using Pandas at all in this project? Pandas datetimes are a bit easier to work with. See [this question](https://stackoverflow.com/questions/13648774/get-year-month-or-day-from-numpy-datetime64) for e.g.. Seems the best method otherwise is just to cast back to a python datetime object. – alkasm Jun 04 '19 at 23:16
  • 1
    e.g.: `[dt for dt in list_dates if dt.astype(object).month in (1, 3)]` (note you can also cast to a `datetime.datetime` if you have that imported already, but `object` works regardless) – alkasm Jun 04 '19 at 23:21

1 Answers1

0

You can make a round trip of parsing and re-formatting your strings, which is going to be cleaner and more scalable.

from datetime import datetime

list_dates = ['2018-06-11','2018-01-01','2018-03-02','2018-12-19','2018-05-19','2017-03-19','2017-02-01','2017-05-30','2016-08-11','2016-06-04','2016-03-11','2016-01-01']

list_dts = [datetime.strptime(x, '%Y-%m-%d') for x in list_dates]

filtered = [dt.strftime('%Y-%m-%d') for dt in list_dts if dt.month in (1, 3)]

# ['2018-01-01', '2018-03-02', '2017-03-19', '2016-03-11', '2016-01-01']
Norrius
  • 7,558
  • 5
  • 40
  • 49