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(['1978-05-19T17:09:49.353584000', '1987-01-23T08:58:01.976823000',
       '1985-11-11T09:57:32.212377000', ...,
       '1978-08-06T02:32:35.664074000', '2004-02-18T08:39:04.254500000',
       '2009-06-01T03:41:21.726774000'], dtype='datetime64[ns]')

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

pyinterp.dateutils.date(dates)
array([(1978,  5, 19), (1987,  1, 23), (1985, 11, 11), ...,
       (1978,  8,  6), (2004,  2, 18), (2009,  6,  1)],
      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([(17,  9, 49), ( 8, 58,  1), ( 9, 57, 32), ..., ( 2, 32, 35),
       ( 8, 39,  4), ( 3, 41, 21)],
      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([(1978, 20, 5), (1987,  4, 5), (1985, 46, 1), ..., (1978, 31, 7),
       (2004,  8, 3), (2009, 23, 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([5, 5, 1, ..., 0, 3, 1], dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)
array([11984989353584000,  1933081976823000, 27165452212377000, ...,
       18757955664074000,  4178344254500000, 13059681726774000],
      dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)
array([datetime.datetime(1978, 5, 19, 17, 9, 49, 353584),
       datetime.datetime(1987, 1, 23, 8, 58, 1, 976823),
       datetime.datetime(1985, 11, 11, 9, 57, 32, 212377), ...,
       datetime.datetime(1978, 8, 6, 2, 32, 35, 664074),
       datetime.datetime(2004, 2, 18, 8, 39, 4, 254500),
       datetime.datetime(2009, 6, 1, 3, 41, 21, 726774)], dtype=object)

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

Gallery generated by Sphinx-Gallery