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()
print(dates)
['1975-01-21T09:54:39.610622000' '1977-03-18T00:12:43.120659000'
 '1983-10-12T01:34:12.779864000' ... '2019-07-18T23:51:58.453253000'
 '1994-06-12T22:34:10.259947000' '1992-06-17T01:10:07.044155000']

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

pyinterp.dateutils.date(dates)
array([(1975,  1, 21), (1977,  3, 18), (1983, 10, 12), ...,
       (2019,  7, 18), (1994,  6, 12), (1992,  6, 17)],
      shape=(10000,), 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([( 9, 54, 39), ( 0, 12, 43), ( 1, 34, 12), ..., (23, 51, 58),
       (22, 34, 10), ( 1, 10,  7)],
      shape=(10000,), 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([(1975,  4, 2), (1977, 11, 5), (1983, 41, 3), ..., (2019, 29, 4),
       (1994, 23, 7), (1992, 25, 3)],
      shape=(10000,), 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, 5, 3, ..., 4, 0, 3], shape=(10000,), dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)
array([ 1763679610622000,  6567163120659000, 24543252779864000, ...,
       17193118453253000, 14078050259947000, 14519407044155000],
      shape=(10000,), dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)
array([datetime.datetime(1975, 1, 21, 9, 54, 39, 610622),
       datetime.datetime(1977, 3, 18, 0, 12, 43, 120659),
       datetime.datetime(1983, 10, 12, 1, 34, 12, 779864), ...,
       datetime.datetime(2019, 7, 18, 23, 51, 58, 453253),
       datetime.datetime(1994, 6, 12, 22, 34, 10, 259947),
       datetime.datetime(1992, 6, 17, 1, 10, 7, 44155)],
      shape=(10000,), dtype=object)

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

Gallery generated by Sphinx-Gallery