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
dates = make_date()
dates

Out:

array(['2014-05-11T23:40:32.700718000', '2003-04-27T21:14:57.835340000',
       '2006-05-27T10:36:27.878868000', ...,
       '1984-05-09T07:33:33.359181000', '2014-05-16T02:36:23.611234000',
       '1991-04-02T06:44:58.591919000'], dtype='datetime64[ns]')

Get the date part as a structured numpy array of three fields: year, month and day:

pyinterp.dateutils.date(dates)

Out:

array([(2014, 5, 11), (2003, 4, 27), (2006, 5, 27), ..., (1984, 5,  9),
       (2014, 5, 16), (1991, 4,  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)

Out:

array([(23, 40, 32), (21, 14, 57), (10, 36, 27), ..., ( 7, 33, 33),
       ( 2, 36, 23), ( 6, 44, 58)],
      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)

Out:

array([(2014, 19, 7), (2003, 17, 7), (2006, 21, 6), ..., (1984, 19, 3),
       (2014, 20, 5), (1991, 14, 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)

Out:

array([0, 0, 6, ..., 3, 5, 2], dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)

Out:

array([11317232700718000, 10098897835340000, 12652587878868000, ...,
       11172813359181000, 11673383611234000,  7886698591919000],
      dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)

Out:

array([datetime.datetime(2014, 5, 11, 23, 40, 32, 700718),
       datetime.datetime(2003, 4, 27, 21, 14, 57, 835340),
       datetime.datetime(2006, 5, 27, 10, 36, 27, 878868), ...,
       datetime.datetime(1984, 5, 9, 7, 33, 33, 359181),
       datetime.datetime(2014, 5, 16, 2, 36, 23, 611234),
       datetime.datetime(1991, 4, 2, 6, 44, 58, 591919)], dtype=object)

Total running time of the script: ( 0 minutes 0.046 seconds)

Gallery generated by Sphinx-Gallery