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(['2017-06-13T07:13:05.648487000', '1978-06-25T11:48:48.603000000',
'1998-01-25T14:05:15.643924000', ...,
'2003-12-29T04:12:31.934470000', '2007-06-19T07:28:11.876077000',
'1987-01-27T19:55:41.243390000'], dtype='datetime64[ns]')
Get the date part as a structured numpy array of three fields: year
,
month
and day
:
pyinterp.dateutils.date(dates)
array([(2017, 6, 13), (1978, 6, 25), (1998, 1, 25), ...,
(2003, 12, 29), (2007, 6, 19), (1987, 1, 27)],
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([( 7, 13, 5), (11, 48, 48), (14, 5, 15), ..., ( 4, 12, 31),
( 7, 28, 11), (19, 55, 41)],
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([(2017, 24, 2), (1978, 25, 7), (1998, 4, 7), ..., (2004, 1, 1),
(2007, 25, 2), (1987, 5, 2)],
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, 0, ..., 1, 2, 2], dtype=uint32)
Get the timedelta from since January
pyinterp.dateutils.timedelta_since_january(dates)
array([14109185648487000, 15162528603000000, 2124315643924000, ...,
31291951934470000, 14628491876077000, 2318141243390000],
dtype='timedelta64[ns]')
Get the dates as datetime.datetime array
pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2017, 6, 13, 7, 13, 5, 648487),
datetime.datetime(1978, 6, 25, 11, 48, 48, 603000),
datetime.datetime(1998, 1, 25, 14, 5, 15, 643924), ...,
datetime.datetime(2003, 12, 29, 4, 12, 31, 934470),
datetime.datetime(2007, 6, 19, 7, 28, 11, 876077),
datetime.datetime(1987, 1, 27, 19, 55, 41, 243390)], dtype=object)
Total running time of the script: (0 minutes 0.041 seconds)