代码之家  ›  专栏  ›  技术社区  ›  mikelowry

使用numpy datetime64如何获得一个月的天数

  •  0
  • mikelowry  · 技术社区  · 3 年前

    在给定的一个月内,最简单、最具吸引力的方法是什么np.datetime64价值观。

    例如: '2020-01-31T00:00:00.000000000' = 31

    我想找一个和 Pandas.daysinmonth ,但对努比来说。

    #pd.daysinmonth example:
    p = pd.Period('2018-2-17')
    p.days_in_month
    28
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   Sayandip Dutta    3 年前

    你可以用 pandas 上的函数 np.datetime64 物体:

    >>> ts = np.datetime64('2020-01-31T00:00:00.000000000')
    >>> ts
    numpy.datetime64('2020-01-31T00:00:00.000000000')
    >>> pd.Period(ts, freq='D').days_in_month
    31
    

    或者,使用 np.datetime_as_string

    >>> pd.Period(np.datetime_as_string(ts)).days_in_month
    31
    

    这是一个纯净的 numpy 解决办法,虽然我有点乐观,但还有一个更好的办法。

    >>> ts = np.datetime64('2020-01-31T00:00:00.000000000')
    >>> def days_in_month(ts):
            ts_month = ts.astype('datetime64[M]')
            return (
                ((ts_month+1).astype('datetime64[D]') - ts_month) 
                // np.timedelta64(1, 'D')
             )
    >>> days_in_month(ts)
    31
    

    它是矢量化的,速度相当快:

    >>> arr = np.arange('2000-01', '2021-12', dtype='datetime64[D]')
    
    >>> arr.shape
    (8005,)
    
    >>> %timeit days_in_month(arr)
    586 µs ± 12.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)