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(['2019-07-30T17:36:33.600023000', '2015-09-27T00:49:28.873214000',
'1990-08-09T19:17:35.059255000', ...,
'2008-01-22T03:30:57.920637000', '1989-12-16T14:52:41.914019000',
'1981-09-28T18:53:32.002698000'], dtype='datetime64[ns]')
Get the date part as a structured numpy array of three fields: year
,
month
and day
:
pyinterp.dateutils.date(dates)
array([(2019, 7, 30), (2015, 9, 27), (1990, 8, 9), ...,
(2008, 1, 22), (1989, 12, 16), (1981, 9, 28)],
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([(17, 36, 33), ( 0, 49, 28), (19, 17, 35), ..., ( 3, 30, 57),
(14, 52, 41), (18, 53, 32)],
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([(2019, 31, 2), (2015, 39, 7), (1990, 32, 4), ..., (2008, 4, 2),
(1989, 50, 6), (1981, 40, 1)],
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, 0, 4, ..., 2, 6, 1], dtype=uint32)
Get the timedelta from since January
pyinterp.dateutils.timedelta_since_january(dates)
array([18207393600023000, 23244568873214000, 19077455059255000, ...,
1827057920637000, 30207161914019000, 23396012002698000],
dtype='timedelta64[ns]')
Get the dates as datetime.datetime array
pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2019, 7, 30, 17, 36, 33, 600023),
datetime.datetime(2015, 9, 27, 0, 49, 28, 873214),
datetime.datetime(1990, 8, 9, 19, 17, 35, 59255), ...,
datetime.datetime(2008, 1, 22, 3, 30, 57, 920637),
datetime.datetime(1989, 12, 16, 14, 52, 41, 914019),
datetime.datetime(1981, 9, 28, 18, 53, 32, 2698)], dtype=object)
Total running time of the script: (0 minutes 0.041 seconds)