Note
Click here to download the full example code or to run this example in your browser via Binder
Numpy date utilities#
This library provides utility functions to perform conversions and get information about numpy dates quickly.
import datetime
import random
import numpy
import pyinterp
def make_date(samples=10000):
"""Generates random dates."""
epoch = datetime.datetime(1970, 1, 1)
delta = datetime.datetime.now() - datetime.datetime(1970, 1, 1)
pydates = [epoch + random.random() * delta for _ in range(samples)]
npdates = numpy.array(pydates).astype('datetime64[ns]')
return npdates
array(['2020-06-02T18:03:39.156520000', '2013-08-26T13:11:35.359262000',
'1994-08-27T02:59:26.771647000', ...,
'1996-06-06T23:06:17.092873000', '2001-09-18T13:34:01.871147000',
'1981-02-04T05:11:10.749162000'], dtype='datetime64[ns]')
Get the date part as a structured numpy array of three fields: year
,
month
and day
:
pyinterp.dateutils.date(dates)
array([(2020, 6, 2), (2013, 8, 26), (1994, 8, 27), ..., (1996, 6, 6),
(2001, 9, 18), (1981, 2, 4)],
dtype=[('year', '<i4'), ('month', '<u4'), ('day', '<u4')])
Get the time part as a structured numpy array of three fields: hour
,
minute
and second
:
pyinterp.dateutils.time(dates)
array([(18, 3, 39), (13, 11, 35), ( 2, 59, 26), ..., (23, 6, 17),
(13, 34, 1), ( 5, 11, 10)],
dtype=[('hour', '<u4'), ('minute', '<u4'), ('second', '<u4')])
Get the ISO calendar of the date as a structured numpy array of three fields:
year
, weekday
and week
:
pyinterp.dateutils.isocalendar(dates)
array([(2020, 23, 2), (2013, 35, 1), (1994, 34, 6), ..., (1996, 23, 4),
(2001, 38, 2), (1981, 6, 3)],
dtype=[('year', '<i4'), ('week', '<u4'), ('weekday', '<u4')])
Get the week day of the dates (Sunday is 0 … Saturday is 6):
pyinterp.dateutils.weekday(dates)
array([2, 1, 6, ..., 4, 2, 3], dtype=uint32)
Get the timedelta from since January
pyinterp.dateutils.timedelta_since_january(dates)
array([13284219156520000, 20524295359262000, 20573966771647000, ...,
13647977092873000, 22512841871147000, 2956270749162000],
dtype='timedelta64[ns]')
Get the dates as datetime.datetime array
pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2020, 6, 2, 18, 3, 39, 156520),
datetime.datetime(2013, 8, 26, 13, 11, 35, 359262),
datetime.datetime(1994, 8, 27, 2, 59, 26, 771647), ...,
datetime.datetime(1996, 6, 6, 23, 6, 17, 92873),
datetime.datetime(2001, 9, 18, 13, 34, 1, 871147),
datetime.datetime(1981, 2, 4, 5, 11, 10, 749162)], dtype=object)
Total running time of the script: ( 0 minutes 0.042 seconds)