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(['1998-02-05T15:32:13.889352000', '1997-01-08T05:24:38.543041000',
       '1977-12-25T06:32:16.896042000', ...,
       '1980-06-29T04:37:32.466673000', '2010-05-22T17:46:57.858642000',
       '1986-10-05T15:04:17.480090000'], 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([(1998,  2,  5), (1997,  1,  8), (1977, 12, 25), ...,
       (1980,  6, 29), (2010,  5, 22), (1986, 10,  5)],
      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([(15, 32, 13), ( 5, 24, 38), ( 6, 32, 16), ..., ( 4, 37, 32),
       (17, 46, 57), (15,  4, 17)],
      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([(1998,  6, 4), (1997,  2, 3), (1977, 51, 7), ..., (1980, 26, 7),
       (2010, 20, 6), (1986, 40, 7)],
      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([4, 3, 0, ..., 0, 6, 0], dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)

Out:

array([ 3079933889352000,   624278543041000, 30954736896042000, ...,
       15568652466673000, 12246417858642000, 23987057480090000],
      dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)

Out:

array([datetime.datetime(1998, 2, 5, 15, 32, 13, 889352),
       datetime.datetime(1997, 1, 8, 5, 24, 38, 543041),
       datetime.datetime(1977, 12, 25, 6, 32, 16, 896042), ...,
       datetime.datetime(1980, 6, 29, 4, 37, 32, 466673),
       datetime.datetime(2010, 5, 22, 17, 46, 57, 858642),
       datetime.datetime(1986, 10, 5, 15, 4, 17, 480090)], dtype=object)

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

Gallery generated by Sphinx-Gallery