Note
Go to the end 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-01-10T21:59:06.979645000', '1977-11-09T04:39:24.193733000',
'1979-05-09T08:56:03.935181000', ...,
'2017-05-02T10:26:55.288149000', '1991-11-30T05:28:43.581342000',
'1990-07-04T15:44:47.473825000'], 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, 1, 10), (1977, 11, 9), (1979, 5, 9), ...,
(2017, 5, 2), (1991, 11, 30), (1990, 7, 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([(21, 59, 6), ( 4, 39, 24), ( 8, 56, 3), ..., (10, 26, 55),
( 5, 28, 43), (15, 44, 47)],
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, 2, 5), (1977, 45, 3), (1979, 19, 3), ..., (2017, 18, 2),
(1991, 48, 6), (1990, 27, 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([5, 3, 3, ..., 2, 6, 3], dtype=uint32)
Get the timedelta from since January
pyinterp.dateutils.timedelta_since_january(dates)
array([ 856746979645000, 26973564193733000, 11091363935181000, ...,
10492015288149000, 28790923581342000, 15954287473825000],
dtype='timedelta64[ns]')
Get the dates as datetime.datetime array
pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2020, 1, 10, 21, 59, 6, 979645),
datetime.datetime(1977, 11, 9, 4, 39, 24, 193733),
datetime.datetime(1979, 5, 9, 8, 56, 3, 935181), ...,
datetime.datetime(2017, 5, 2, 10, 26, 55, 288149),
datetime.datetime(1991, 11, 30, 5, 28, 43, 581342),
datetime.datetime(1990, 7, 4, 15, 44, 47, 473825)], dtype=object)
Total running time of the script: ( 0 minutes 0.038 seconds)