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(['2007-09-16T00:49:13.167795000', '1997-12-27T23:54:33.365413000',
'2001-05-12T04:01:06.817499000', ...,
'2015-01-19T04:52:41.518472000', '1981-04-21T11:09:00.544827000',
'2021-03-31T07:17:22.694690000'], dtype='datetime64[ns]')
Get the date part as a structured numpy array of three fields: year
,
month
and day
:
pyinterp.dateutils.date(dates)
array([(2007, 9, 16), (1997, 12, 27), (2001, 5, 12), ...,
(2015, 1, 19), (1981, 4, 21), (2021, 3, 31)],
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([( 0, 49, 13), (23, 54, 33), ( 4, 1, 6), ..., ( 4, 52, 41),
(11, 9, 0), ( 7, 17, 22)],
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([(2007, 37, 7), (1997, 52, 6), (2001, 19, 6), ..., (2015, 4, 1),
(1981, 17, 2), (2021, 13, 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([0, 6, 6, ..., 1, 2, 3], dtype=uint32)
Get the timedelta from since January
pyinterp.dateutils.timedelta_since_january(dates)
array([22294153167795000, 31190073365413000, 11332866817499000, ...,
1572761518472000, 9544140544827000, 7715842694690000],
dtype='timedelta64[ns]')
Get the dates as datetime.datetime array
pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2007, 9, 16, 0, 49, 13, 167795),
datetime.datetime(1997, 12, 27, 23, 54, 33, 365413),
datetime.datetime(2001, 5, 12, 4, 1, 6, 817499), ...,
datetime.datetime(2015, 1, 19, 4, 52, 41, 518472),
datetime.datetime(1981, 4, 21, 11, 9, 0, 544827),
datetime.datetime(2021, 3, 31, 7, 17, 22, 694690)], dtype=object)
Total running time of the script: (0 minutes 0.040 seconds)