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)
['2021-07-08T23:27:01.728351000' '1986-01-06T22:19:53.876026000'
 '2014-08-22T03:48:47.576783000' ... '1972-07-08T02:22:03.425555000'
 '2024-06-20T17:24:15.309957000' '2002-04-21T19:33:09.506837000']

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

pyinterp.dateutils.date(dates)
array([(2021, 7,  8), (1986, 1,  6), (2014, 8, 22), ..., (1972, 7,  8),
       (2024, 6, 20), (2002, 4, 21)],
      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([(23, 27,  1), (22, 19, 53), ( 3, 48, 47), ..., ( 2, 22,  3),
       (17, 24, 15), (19, 33,  9)],
      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([(2021, 27, 4), (1986,  2, 1), (2014, 34, 5), ..., (1972, 27, 6),
       (2024, 25, 4), (2002, 16, 7)],
      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([4, 1, 5, ..., 6, 4, 0], shape=(10000,), dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)
array([16327621728351000,   512393876026000, 20144927576783000, ...,
       16338123425555000, 14837055309957000,  9574389506837000],
      shape=(10000,), dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)
array([datetime.datetime(2021, 7, 8, 23, 27, 1, 728351),
       datetime.datetime(1986, 1, 6, 22, 19, 53, 876026),
       datetime.datetime(2014, 8, 22, 3, 48, 47, 576783), ...,
       datetime.datetime(1972, 7, 8, 2, 22, 3, 425555),
       datetime.datetime(2024, 6, 20, 17, 24, 15, 309957),
       datetime.datetime(2002, 4, 21, 19, 33, 9, 506837)],
      shape=(10000,), dtype=object)

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

Gallery generated by Sphinx-Gallery