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(['1987-05-29T19:41:33.349756000', '1980-12-08T12:03:46.351324000',
       '1972-05-10T19:55:30.517444000', ...,
       '1987-07-26T03:26:03.243674000', '1989-04-21T08:01:02.113451000',
       '2007-09-12T22:50:45.860993000'], dtype='datetime64[ns]')

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

pyinterp.dateutils.date(dates)
array([(1987,  5, 29), (1980, 12,  8), (1972,  5, 10), ...,
       (1987,  7, 26), (1989,  4, 21), (2007,  9, 12)],
      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([(19, 41, 33), (12,  3, 46), (19, 55, 30), ..., ( 3, 26,  3),
       ( 8,  1,  2), (22, 50, 45)],
      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([(1987, 22, 5), (1980, 50, 1), (1972, 19, 3), ..., (1987, 30, 7),
       (1989, 16, 5), (2007, 37, 3)],
      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, 1, 3, ..., 0, 5, 3], dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)
array([12858093349756000, 29592226351324000, 11303730517444000, ...,
       17810763243674000,  9532862113451000, 22027845860993000],
      dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)
array([datetime.datetime(1987, 5, 29, 19, 41, 33, 349756),
       datetime.datetime(1980, 12, 8, 12, 3, 46, 351324),
       datetime.datetime(1972, 5, 10, 19, 55, 30, 517444), ...,
       datetime.datetime(1987, 7, 26, 3, 26, 3, 243674),
       datetime.datetime(1989, 4, 21, 8, 1, 2, 113451),
       datetime.datetime(2007, 9, 12, 22, 50, 45, 860993)], dtype=object)

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

Gallery generated by Sphinx-Gallery