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(['1981-05-03T10:51:24.417011000', '2021-01-15T16:07:42.615462000',
       '1985-12-30T13:04:06.379130000', ...,
       '1987-04-16T22:36:10.925306000', '1988-07-14T20:10:08.546607000',
       '2020-12-04T03:06:10.769907000'], dtype='datetime64[ns]')

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

pyinterp.dateutils.date(dates)
array([(1981,  5,  3), (2021,  1, 15), (1985, 12, 30), ...,
       (1987,  4, 16), (1988,  7, 14), (2020, 12,  4)],
      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([(10, 51, 24), (16,  7, 42), (13,  4,  6), ..., (22, 36, 10),
       (20, 10,  8), ( 3,  6, 10)],
      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([(1981, 18, 7), (2021,  2, 5), (1986,  1, 1), ..., (1987, 16, 4),
       (1988, 28, 4), (2020, 49, 5)],
      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([0, 5, 1, ..., 4, 4, 5], dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)
array([10579884417011000,  1267662615462000, 31410246379130000, ...,
        9153370925306000, 16920608546607000, 29214370769907000],
      dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)
array([datetime.datetime(1981, 5, 3, 10, 51, 24, 417011),
       datetime.datetime(2021, 1, 15, 16, 7, 42, 615462),
       datetime.datetime(1985, 12, 30, 13, 4, 6, 379130), ...,
       datetime.datetime(1987, 4, 16, 22, 36, 10, 925306),
       datetime.datetime(1988, 7, 14, 20, 10, 8, 546607),
       datetime.datetime(2020, 12, 4, 3, 6, 10, 769907)], dtype=object)

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

Gallery generated by Sphinx-Gallery