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(['1975-09-13T20:24:56.103533000', '1977-02-18T08:43:10.492623000',
       '1981-06-03T17:28:29.784301000', ...,
       '1985-02-01T13:20:05.674729000', '1992-02-19T02:03:07.717998000',
       '1971-02-24T05:30:00.819357000'], dtype='datetime64[ns]')

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

pyinterp.dateutils.date(dates)
array([(1975, 9, 13), (1977, 2, 18), (1981, 6,  3), ..., (1985, 2,  1),
       (1992, 2, 19), (1971, 2, 24)],
      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([(20, 24, 56), ( 8, 43, 10), (17, 28, 29), ..., (13, 20,  5),
       ( 2,  3,  7), ( 5, 30,  0)],
      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, 37, 6), (1977,  7, 5), (1981, 23, 3), ..., (1985,  5, 5),
       (1992,  8, 3), (1971,  8, 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([6, 5, 3, ..., 5, 3, 3], dtype=uint32)

Get the timedelta from since January

pyinterp.dateutils.timedelta_since_january(dates)
array([22105496103533000,  4178590492623000, 13282109784301000, ...,
        2726405674729000,  4240987717998000,  4685400819357000],
      dtype='timedelta64[ns]')

Get the dates as datetime.datetime array

pyinterp.dateutils.datetime(dates)
array([datetime.datetime(1975, 9, 13, 20, 24, 56, 103533),
       datetime.datetime(1977, 2, 18, 8, 43, 10, 492623),
       datetime.datetime(1981, 6, 3, 17, 28, 29, 784301), ...,
       datetime.datetime(1985, 2, 1, 13, 20, 5, 674729),
       datetime.datetime(1992, 2, 19, 2, 3, 7, 717998),
       datetime.datetime(1971, 2, 24, 5, 30, 0, 819357)], dtype=object)

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

Gallery generated by Sphinx-Gallery