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
['2004-06-15T22:15:13.842235000' '1978-10-12T12:26:42.392722000'
'2018-06-08T16:09:20.417184000' ... '1975-07-20T04:59:17.432479000'
'1973-10-08T07:13:16.558973000' '1970-02-06T21:33:13.977613000']
Get the date part as a structured numpy array of three fields: year
,
month
and day
:
pyinterp.dateutils.date(dates)
array([(2004, 6, 15), (1978, 10, 12), (2018, 6, 8), ...,
(1975, 7, 20), (1973, 10, 8), (1970, 2, 6)],
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([(22, 15, 13), (12, 26, 42), (16, 9, 20), ..., ( 4, 59, 17),
( 7, 13, 16), (21, 33, 13)],
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([(2004, 25, 2), (1978, 41, 4), (2018, 23, 5), ..., (1975, 29, 7),
(1973, 41, 1), (1970, 6, 5)],
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, 4, 5, ..., 0, 1, 5], dtype=uint32)
Get the timedelta from since January
pyinterp.dateutils.timedelta_since_january(dates)
array([14422513842235000, 24582402392722000, 13709360417184000, ...,
17297957432479000, 24217996558973000, 3187993977613000],
dtype='timedelta64[ns]')
Get the dates as datetime.datetime array
pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2004, 6, 15, 22, 15, 13, 842235),
datetime.datetime(1978, 10, 12, 12, 26, 42, 392722),
datetime.datetime(2018, 6, 8, 16, 9, 20, 417184), ...,
datetime.datetime(1975, 7, 20, 4, 59, 17, 432479),
datetime.datetime(1973, 10, 8, 7, 13, 16, 558973),
datetime.datetime(1970, 2, 6, 21, 33, 13, 977613)], dtype=object)
Total running time of the script: (0 minutes 0.030 seconds)