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
array(['1986-08-14T04:08:29.227194000', '1999-12-11T11:47:06.945868000',
       '1973-12-07T13:37:37.982956000', ...,
       '1996-12-04T15:13:45.164899000', '1991-06-12T12:50:51.377510000',
       '1996-12-23T16:30:54.934839000'], dtype='datetime64[ns]')

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

pyinterp.dateutils.date(dates)
array([(1986,  8, 14), (1999, 12, 11), (1973, 12,  7), ...,
       (1996, 12,  4), (1991,  6, 12), (1996, 12, 23)],
      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([( 4,  8, 29), (11, 47,  6), (13, 37, 37), ..., (15, 13, 45),
       (12, 50, 51), (16, 30, 54)],
      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([(1986, 33, 4), (1999, 49, 6), (1973, 49, 5), ..., (1996, 49, 3),
       (1991, 24, 3), (1996, 52, 1)],
      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([4, 6, 5, ..., 3, 3, 1], dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)
array([19454909227194000, 29764026945868000, 29425057982956000, ...,
       29258025164899000, 14043051377510000, 30904254934839000],
      dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)
array([datetime.datetime(1986, 8, 14, 4, 8, 29, 227194),
       datetime.datetime(1999, 12, 11, 11, 47, 6, 945868),
       datetime.datetime(1973, 12, 7, 13, 37, 37, 982956), ...,
       datetime.datetime(1996, 12, 4, 15, 13, 45, 164899),
       datetime.datetime(1991, 6, 12, 12, 50, 51, 377510),
       datetime.datetime(1996, 12, 23, 16, 30, 54, 934839)], dtype=object)

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

Gallery generated by Sphinx-Gallery