且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取多个日期时间对的日期范围

更新时间:2023-09-19 13:44:16

这有点令人费解……
但是

It's a tad convoluted...
But

d = np.array(1, dtype='timedelta64[D]')
x = x.astype('datetime64[D]')
deltas = np.diff(x, axis=1) / d
np.concatenate([
    i + np.arange(j + 1) for i, j in zip(x[:, 0], deltas[:, 0].astype(int))
]).astype('datetime64[ns]')

array(['2017-10-02T00:00:00.000000000', '2017-10-03T00:00:00.000000000',
       '2017-10-04T00:00:00.000000000', '2017-10-05T00:00:00.000000000',
       '2017-10-06T00:00:00.000000000', '2017-10-07T00:00:00.000000000',
       '2017-10-08T00:00:00.000000000', '2017-10-09T00:00:00.000000000',
       '2017-10-10T00:00:00.000000000', '2017-10-11T00:00:00.000000000',
       '2017-10-12T00:00:00.000000000'], dtype='datetime64[ns]')


工作方式

  • d代表一天
  • x变成没有时间戳的日期
  • diff为我提供了天差...但是在timedelta空间
  • 我将我的d除以同样位于timedelta的空间,并且尺寸消失了……剩下的是float,我将其投射为int
  • 当我将对x[:, 0]中的第一列添加到整数数组时,我得到广播,添加了一个任意维度的单元,无论维度是x还是datetime64[D].所以我要增加一天.
  • d represents one day
  • x is turned into dates with no timestamps
  • diff gets me the number of days difference... but in timedelta space
  • I divide by my d which is also in timedelta space and the dimensions disappear... leaving me with float which I cast to int
  • When I add the first column of the pairs x[:, 0] to an array of integers, I get a broadcasting of adding 1 unit of whatever the dimension is of x, which is datetime64[D]. So I'm adding one day.

源自@hpaulj或受其启发
如果他们发布答案将会删除

Derived from / Inspired by @hpaulj
Will remove if they post an answer

d = np.array(1, dtype='timedelta64[D]')
np.concatenate([np.arange(row[0], row[1] + 1, d) for row in x])

array(['2017-10-02T00:00:00.000000000', '2017-10-03T00:00:00.000000000',
       '2017-10-04T00:00:00.000000000', '2017-10-05T00:00:00.000000000',
       '2017-10-06T00:00:00.000000000', '2017-10-07T00:00:00.000000000',
       '2017-10-08T00:00:00.000000000', '2017-10-09T00:00:00.000000000',
       '2017-10-10T00:00:00.000000000', '2017-10-11T00:00:00.000000000',
       '2017-10-12T00:00:00.000000000'], dtype='datetime64[ns]')