所以我有以下日期列表
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')]
我只想生成一个新的列表,其中包含1月和3月的月份。
所需的输出看起来像这样:
[np.datetime64('2018-01-01'),np.datetime64('2018-03-02'),np.datetime64('2017-03-19'),
np.datetime64('2016-03-11')]
我当时以为我要用弦乐,所以我做到了
dates_selected=[x for x in list_dates if "-03-" in x ]+
[x for x in list_dates if "-01-" in x ]
问题是我收到一个输出,指示:
TypeError: arguments of type numpy.datetime64 is not iterable
考虑到我用datetime64而不是字符串处理,如何获得所需的输出?
答案 0 :(得分:0)
您可以使parsing and re-formatting的字符串来回移动,这将使字符串更干净,更具伸缩性。
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']