Note
Click here 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(['2015-10-12T15:14:41.742514000', '1974-05-13T06:59:22.979188000',
'1976-11-18T21:18:11.414227000', ...,
'1971-06-10T12:17:24.979057000', '2014-07-06T12:21:20.741196000',
'1979-03-02T17:05:30.645873000'], dtype='datetime64[ns]')
Get the date part as a structured numpy array of three fields: year
,
month
and day
:
pyinterp.dateutils.date(dates)
array([(2015, 10, 12), (1974, 5, 13), (1976, 11, 18), ...,
(1971, 6, 10), (2014, 7, 6), (1979, 3, 2)],
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([(15, 14, 41), ( 6, 59, 22), (21, 18, 11), ..., (12, 17, 24),
(12, 21, 20), (17, 5, 30)],
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([(2015, 42, 1), (1974, 20, 1), (1976, 47, 4), ..., (1971, 23, 4),
(2014, 27, 7), (1979, 9, 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([1, 1, 4, ..., 4, 0, 5], dtype=uint32)
Get the timedelta from since January
pyinterp.dateutils.timedelta_since_january(dates)
array([24592481742514000, 11429962979188000, 27897491414227000, ...,
13868244979057000, 16114880741196000, 5245530645873000],
dtype='timedelta64[ns]')
Get the dates as datetime.datetime array
pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2015, 10, 12, 15, 14, 41, 742514),
datetime.datetime(1974, 5, 13, 6, 59, 22, 979188),
datetime.datetime(1976, 11, 18, 21, 18, 11, 414227), ...,
datetime.datetime(1971, 6, 10, 12, 17, 24, 979057),
datetime.datetime(2014, 7, 6, 12, 21, 20, 741196),
datetime.datetime(1979, 3, 2, 17, 5, 30, 645873)], dtype=object)
Total running time of the script: ( 0 minutes 0.039 seconds)