8

我有一个日期时间对象列表,并希望找到在特定时间范围内的对象:

import datetime

dates = [ datetime.datetime(2007, 1, 2, 0, 1),
          datetime.datetime(2007, 1, 3, 0, 2),
          datetime.datetime(2007, 1, 4, 0, 3),
          datetime.datetime(2007, 1, 5, 0, 4),
          datetime.datetime(2007, 1, 6, 0, 5),
          datetime.datetime(2007, 1, 7, 0, 6) ]
#in reality this is a list of over 25000 dates

mask = (dates>datetime.datetime(2007,1,3)) & \
       (dates<datetime.datetime(2007,1,6))

但是,这会导致以下错误:“TypeError: can't compare datetime.datetime to list”

如何修复我的代码?

4

3 回答 3

12

numpy.array您可以在您描述的语法中屏蔽 a (但不是列表)

import numpy as np

date1 = np.array(dates)
mask = (dates1 > datetime.datetime(2007,1,3)) & \
       (dates1 < datetime.datetime(2007,1,6))

In [14]: mask
Out[14]: array([False,  True,  True,  True, False, False], dtype=bool)

In [15]: dates1[mask]
Out[15]: array([2007-01-03 00:02:00, 2007-01-04 00:03:00, 2007-01-05 00:04:00], dtype=object)

(因为这个问题被标记为 numpy,大概这就是你想要的。)

于 2013-01-03T16:39:00.570 回答
11

如果您的dates列表按排序顺序,您可以使用该bisect模块

>>> import bisect
>>> bisect.bisect_right(dates, datetime.datetime(2007,1,3))
1
>>> bisect.bisect_left(dates, datetime.datetime(2007,1,6))
4

这些.bisect_*函数将索引返回到dates列表中:

>>> lower = bisect.bisect_right(dates, datetime.datetime(2007,1,3))
>>> upper = bisect.bisect_left(dates, datetime.datetime(2007,1,6))
>>> mask = dates[lower:upper]
>>> mask
[datetime.datetime(2007, 1, 3, 0, 2), datetime.datetime(2007, 1, 4, 0, 3), datetime.datetime(2007, 1, 5, 0, 4)]
于 2013-01-03T16:39:15.523 回答
5
import datetime

dates = [ datetime.datetime(2007, 1, 2, 0, 1),
          datetime.datetime(2007, 1, 3, 0, 2),
          datetime.datetime(2007, 1, 4, 0, 3),
          datetime.datetime(2007, 1, 5, 0, 4),
          datetime.datetime(2007, 1, 6, 0, 5),
          datetime.datetime(2007, 1, 7, 0, 6) ]


within = [date for date in dates if datetime.datetime(2007,1,3) < date < datetime.datetime(2007,1,6)]

产量:

[datetime.datetime(2007, 1, 3, 0, 2), 
 datetime.datetime(2007, 1, 4, 0, 3), 
 datetime.datetime(2007, 1, 5, 0, 4)]
于 2013-01-03T16:40:23.497 回答