numpy  2.0.0
src/multiarray/datetime.c File Reference
#include <Python.h>
#include <datetime.h>
#include <time.h>
#include <numpy/arrayobject.h>
#include "npy_config.h"
#include "npy_pycompat.h"
#include "numpy/arrayscalars.h"
#include "methods.h"
#include "_datetime.h"
#include "datetime_strings.h"

Defines

#define PY_SSIZE_T_CLEAN
#define NPY_NO_DEPRECATED_API   NPY_API_VERSION
#define _MULTIARRAYMODULE

Functions

NPY_NO_EXPORT void numpy_pydatetime_import (void)
NPY_NO_EXPORT int is_leapyear (npy_int64 year)
NPY_NO_EXPORT npy_int64 get_datetimestruct_days (const npy_datetimestruct *dts)
NPY_NO_EXPORT npy_int64 get_datetimestruct_minutes (const npy_datetimestruct *dts)
static npy_int64 days_to_yearsdays (npy_int64 *days_)
NPY_NO_EXPORT int days_to_month_number (npy_datetime days)
static void set_datetimestruct_days (npy_int64 days, npy_datetimestruct *dts)
NPY_NO_EXPORT int convert_datetimestruct_to_datetime (PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, npy_datetime *out)
NPY_NO_EXPORT npy_datetime PyArray_DatetimeStructToDatetime (NPY_DATETIMEUNIT fr, npy_datetimestruct *d)
NPY_NO_EXPORT npy_datetime PyArray_TimedeltaStructToTimedelta (NPY_DATETIMEUNIT fr, npy_timedeltastruct *d)
NPY_NO_EXPORT int convert_datetime_to_datetimestruct (PyArray_DatetimeMetaData *meta, npy_datetime dt, npy_datetimestruct *out)
NPY_NO_EXPORT void PyArray_DatetimeToDatetimeStruct (npy_datetime val, NPY_DATETIMEUNIT fr, npy_datetimestruct *result)
NPY_NO_EXPORT void PyArray_TimedeltaToTimedeltaStruct (npy_timedelta val, NPY_DATETIMEUNIT fr, npy_timedeltastruct *result)
NPY_NO_EXPORT PyArray_Descrcreate_datetime_dtype (int type_num, PyArray_DatetimeMetaData *meta)
NPY_NO_EXPORT PyArray_Descrcreate_datetime_dtype_with_unit (int type_num, NPY_DATETIMEUNIT unit)
NPY_NO_EXPORT
PyArray_DatetimeMetaData
get_datetime_metadata_from_dtype (PyArray_Descr *dtype)
NPY_NO_EXPORT int parse_datetime_extended_unit_from_string (char *str, Py_ssize_t len, char *metastr, PyArray_DatetimeMetaData *out_meta)
NPY_NO_EXPORT int parse_datetime_metadata_from_metastr (char *metastr, Py_ssize_t len, PyArray_DatetimeMetaData *out_meta)
NPY_NO_EXPORT PyArray_Descrparse_dtype_from_datetime_typestr (char *typestr, Py_ssize_t len)
NPY_NO_EXPORT int convert_datetime_divisor_to_multiple (PyArray_DatetimeMetaData *meta, int den, char *metastr)
static npy_uint64 get_datetime_units_factor (NPY_DATETIMEUNIT bigbase, NPY_DATETIMEUNIT littlebase)
static npy_uint64 _uint64_euclidean_gcd (npy_uint64 x, npy_uint64 y)
NPY_NO_EXPORT void get_datetime_conversion_factor (PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_int64 *out_num, npy_int64 *out_denom)
NPY_NO_EXPORT npy_bool datetime_metadata_divides (PyArray_DatetimeMetaData *dividend, PyArray_DatetimeMetaData *divisor, int strict_with_nonlinear_units)
NPY_NO_EXPORT npy_bool can_cast_datetime64_units (NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting)
NPY_NO_EXPORT npy_bool can_cast_timedelta64_units (NPY_DATETIMEUNIT src_unit, NPY_DATETIMEUNIT dst_unit, NPY_CASTING casting)
NPY_NO_EXPORT npy_bool can_cast_datetime64_metadata (PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting)
NPY_NO_EXPORT npy_bool can_cast_timedelta64_metadata (PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting)
NPY_NO_EXPORT int raise_if_datetime64_metadata_cast_error (char *object_type, PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting)
NPY_NO_EXPORT int raise_if_timedelta64_metadata_cast_error (char *object_type, PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting)
NPY_NO_EXPORT int compute_datetime_metadata_greatest_common_divisor (PyArray_DatetimeMetaData *meta1, PyArray_DatetimeMetaData *meta2, PyArray_DatetimeMetaData *out_meta, int strict_with_nonlinear_units1, int strict_with_nonlinear_units2)
NPY_NO_EXPORT PyArray_Descrdatetime_type_promotion (PyArray_Descr *type1, PyArray_Descr *type2)
NPY_NO_EXPORT NPY_DATETIMEUNIT parse_datetime_unit_from_string (char *str, Py_ssize_t len, char *metastr)
NPY_NO_EXPORT PyObject * convert_datetime_metadata_to_tuple (PyArray_DatetimeMetaData *meta)
NPY_NO_EXPORT int convert_datetime_metadata_tuple_to_datetime_metadata (PyObject *tuple, PyArray_DatetimeMetaData *out_meta)
NPY_NO_EXPORT int convert_pyobject_to_datetime_metadata (PyObject *obj, PyArray_DatetimeMetaData *out_meta)
NPY_NO_EXPORT PyObject * append_metastr_to_string (PyArray_DatetimeMetaData *meta, int skip_brackets, PyObject *ret)
NPY_NO_EXPORT void add_seconds_to_datetimestruct (npy_datetimestruct *dts, int seconds)
NPY_NO_EXPORT void add_minutes_to_datetimestruct (npy_datetimestruct *dts, int minutes)
NPY_NO_EXPORT int convert_pydatetime_to_datetimestruct (PyObject *obj, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo)
NPY_NO_EXPORT int get_tzoffset_from_pytzinfo (PyObject *timezone_obj, npy_datetimestruct *dts)
NPY_NO_EXPORT int convert_pyobject_to_datetime (PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_datetime *out)
NPY_NO_EXPORT int convert_pyobject_to_timedelta (PyArray_DatetimeMetaData *meta, PyObject *obj, NPY_CASTING casting, npy_timedelta *out)
NPY_NO_EXPORT PyObject * convert_datetime_to_pyobject (npy_datetime dt, PyArray_DatetimeMetaData *meta)
NPY_NO_EXPORT PyObject * convert_timedelta_to_pyobject (npy_timedelta td, PyArray_DatetimeMetaData *meta)
NPY_NO_EXPORT npy_bool has_equivalent_datetime_metadata (PyArray_Descr *type1, PyArray_Descr *type2)
NPY_NO_EXPORT int cast_datetime_to_datetime (PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_datetime src_dt, npy_datetime *dst_dt)
NPY_NO_EXPORT int cast_timedelta_to_timedelta (PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, npy_timedelta src_dt, npy_timedelta *dst_dt)
static NPY_GCC_NONNULL (1)
static npy_bool is_any_numpy_timedelta (PyObject *obj)
NPY_NO_EXPORT npy_bool is_any_numpy_datetime_or_timedelta (PyObject *obj)
NPY_NO_EXPORT int convert_pyobjects_to_datetimes (int count, PyObject **objs, int *type_nums, NPY_CASTING casting, npy_int64 *out_values, PyArray_DatetimeMetaData *inout_meta)
NPY_NO_EXPORT PyArrayObjectdatetime_arange (PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype)
static int find_string_array_datetime64_type (PyArrayObject *arr, PyArray_DatetimeMetaData *meta)
static int recursive_find_object_datetime64_type (PyObject *obj, PyArray_DatetimeMetaData *meta)
static int recursive_find_object_timedelta64_type (PyObject *obj, PyArray_DatetimeMetaData *meta)
NPY_NO_EXPORT PyArray_Descrfind_object_datetime_type (PyObject *obj, int type_num)

Variables

NPY_NO_EXPORT char * _datetime_strings [NPY_DATETIME_NUMUNITS]
NPY_NO_EXPORT int _days_per_month_table [2][12]
static NPY_DATETIMEUNIT _multiples_table [16][4]
static npy_uint32 _datetime_factors []

Define Documentation

#define NPY_NO_DEPRECATED_API   NPY_API_VERSION

Function Documentation

static npy_uint64 _uint64_euclidean_gcd ( npy_uint64  x,
npy_uint64  y 
) [static]
Euclidean algorithm on two positive numbers

References NPY_FR_GENERIC.

Adjusts a datetimestruct based on a minutes offset. Assumes the current values are valid.
MINUTES
HOURS
DAYS

Referenced by convert_pyobject_to_datetime_metadata(), and datetime_type_promotion().

Adjusts a datetimestruct based on a seconds offset. Assumes the current values are valid.
NPY_NO_EXPORT PyObject* append_metastr_to_string ( PyArray_DatetimeMetaData meta,
int  skip_brackets,
PyObject *  ret 
)
'ret' is a PyUString containing the datetime string, and this function appends the metadata string to it.
If 'skip_brackets' is true, skips the '[]'.
This function steals the reference 'ret'
Without brackets, give a string "generic"
But with brackets, append nothing

Referenced by name().

This provides the casting rules for the DATETIME data type metadata.
This provides the casting rules for the DATETIME data type units.
Allow anything with unsafe casting
Can cast between all units with 'same_kind' casting.
Casting is only allowed towards more precise units with 'safe' casting.
Enforce equality with 'no' or 'equiv' casting

Referenced by parse_iso_8601_datetime().

This provides the casting rules for the TIMEDELTA data type metadata.
This provides the casting rules for the TIMEDELTA data type units.
Notably, there is a barrier between the nonlinear years and months units, and all the other units.
Allow anything with unsafe casting
Only enforce the 'date units' vs 'time units' barrier with 'same_kind' casting.
Enforce the 'date units' vs 'time units' barrier and that casting is only allowed towards more precise units with 'safe' casting.
Enforce equality with 'no' or 'equiv' casting
Casts a single datetime from having src_meta metadata into dst_meta metadata.
Returns 0 on success, -1 on failure.
If the metadata is the same, short-circuit the conversion
Otherwise convert through a datetimestruct

References compute_datetime_metadata_greatest_common_divisor(), find_string_array_datetime64_type(), get_datetime_metadata_from_dtype(), NPY_DATETIME, NPY_OBJECT, NPY_STRING, NPY_TIMEDELTA, NPY_UNICODE, PyArray_DESCR, and _PyArray_Descr::type_num.

Casts a single timedelta from having src_meta metadata into dst_meta metadata.
Returns 0 on success, -1 on failure.
If the metadata is the same, short-circuit the conversion
Get the conversion factor
Apply the scaling
NPY_NO_EXPORT int compute_datetime_metadata_greatest_common_divisor ( PyArray_DatetimeMetaData meta1,
PyArray_DatetimeMetaData meta2,
PyArray_DatetimeMetaData out_meta,
int  strict_with_nonlinear_units1,
int  strict_with_nonlinear_units2 
)
Computes the GCD of the two date-time metadata values. Raises an exception if there is no reasonable GCD, such as with years and days.
The result is placed in 'out_meta'.
Returns 0 on success, -1 on failure.
If either unit is generic, adopt the metadata from the other one
First validate that the units have a reasonable GCD
Years and Months are incompatible with all other units (except years and months are compatible with each other).
Don't multiply num1 since there is no even factor
Don't multiply num2 since there is no even factor
Don't multiply num1 since there is no even factor
Don't multiply num2 since there is no even factor
Take the greater base (unit sizes are decreasing in enum)
Compute the GCD of the resulting multipliers
Fill the 'out_meta' values

Referenced by cast_datetime_to_datetime().

NPY_NO_EXPORT int convert_datetime_divisor_to_multiple ( PyArray_DatetimeMetaData meta,
int  den,
char *  metastr 
)
Translate divisors into multiples of smaller units. 'metastr' is used for the error message if the divisor doesn't work, and can be NULL if the metadata didn't come from a string.
This function only affects the 'base' and 'num' values in the metadata.
Returns 0 on success, -1 on failure.
Given a pointer to datetime metadata, returns a tuple for pickling and other purposes.
Converts a metadata tuple into a datetime metadata C struct.
Returns 0 on success, -1 on failure.
Allow unicode format strings: convert to bytes
Convert the values to longs
Converts a datetime based on the given metadata into a datetimestruct
Initialize the output to all zeros
NaT is signaled in the year
Datetimes can't be in generic units
TODO: Change to a mechanism that avoids the potential overflow
Note that care must be taken with the / and % operators for negative values.
A week is 7 days
entire range is only +- 2.6 hours
Offset the negative minutes
entire range is only +- 9.2 seconds
Offset the negative seconds
Converts a datetime into a PyObject *.

System Message: WARNING/2 (<string>, line 1); backlink Inline emphasis start-string without end-string.
Not-a-time is returned as the string "NaT". For days or coarser, returns a datetime.date. For microseconds or coarser, returns a datetime.datetime. For units finer than microseconds, returns an integer.
Convert NaT (not-a-time) and any value with generic units into None.
If the type's precision is greater than microseconds, return an int
Convert to a datetimestruct
If the year is outside the range of years supported by Python's datetime, or the datetime64 falls on a leap second, return a raw int.
If the type's precision is greater than days, return a datetime
Otherwise return a date
Converts a datetime from a datetimestruct to a datetime based on some metadata. The date is assumed to be valid.
TODO: If meta->num is really big, there could be overflow
Returns 0 on success, -1 on failure.
If the datetimestruct is NaT, return NaT
Cannot instantiate a datetime with generic units
Truncate to the year
Truncate to the month
Otherwise calculate the number of days to start
Truncate to weeks
only 2.6 hours
only 9.2 secs
Something got corrupted
Divide by the multiplier
NPY_NO_EXPORT int convert_pydatetime_to_datetimestruct ( PyObject *  obj,
npy_datetimestruct out,
NPY_DATETIMEUNIT out_bestunit,
int  apply_tzinfo 
)
Tests for and converts a Python datetime.datetime or datetime.date object into a NumPy npy_datetimestruct.
While the C API has PyDate_* and PyDateTime_* functions, the following implementation just asks for attributes, and thus supports datetime duck typing. The tzinfo time zone conversion would require this style of access anyway.

'out_bestunit' gives a suggested unit based on whether the object
was a datetime.date or datetime.datetime object.
If 'apply_tzinfo' is 1, this function uses the tzinfo to convert to UTC time, otherwise it returns the struct with the local time.
Returns -1 on error, 0 on success, and 1 (with no error set) if obj doesn't have the neeeded date or datetime attributes.
Initialize the output to all zeros
Need at least year/month/day attributes
Get the year
Get the month
Get the day
Validate that the month and day are valid for the year
Check for time attributes (if not there, return success as a date)
The best unit for date is 'D'
Get the hour
Get the minute
Get the second
Get the microsecond
Apply the time zone offset if it exists
2016-01-14, 1.11
The utcoffset function should return a timedelta
The timedelta should have a function "total_seconds" which contains the value we want.
Convert to a minutes offset and apply it
The resolution of Python's datetime is 'us'
NPY_NO_EXPORT int convert_pyobject_to_datetime ( PyArray_DatetimeMetaData meta,
PyObject *  obj,
NPY_CASTING  casting,
npy_datetime out 
)
Converts a PyObject * into a datetime, in any of the forms supported.
If the units metadata isn't known ahead of time, set meta->base to -1, and this function will populate meta with either default values or values from the input object.
The 'casting' parameter is used to control what kinds of inputs are accepted, and what happens. For example, with 'unsafe' casting, unrecognized inputs are converted to 'NaT' instead of throwing an error, while with 'safe' casting an error will be thrown if any precision from the input will be thrown away.
Returns -1 on error, 0 on success.
Convert to an ASCII string for the date parser
Parse the ISO date
Use the detected unit if none was specified
Do no conversion on raw integers
Don't allow conversion from an integer without specifying a unit
Datetime scalar
Copy the scalar directly if units weren't specified
Otherwise do a casting transformation
Allow NaT (not-a-time) values to slip through any rule
Datetime zero-dimensional array
Copy the value directly if units weren't specified
Otherwise do a casting transformation
Allow NaT (not-a-time) values to slip through any rule
Convert from a Python date or datetime object
Use the detected unit if none was specified
With unsafe casting, convert unrecognized objects into NaT and with same_kind casting, convert None into NaT
Converts an input object into datetime metadata. The input may be either a string or a tuple.
Returns 0 on success, -1 on failure.
Get an ASCII string
Allow unicode format strings: convert to bytes

References add_minutes_to_datetimestruct(), and DEPRECATE.

NPY_NO_EXPORT int convert_pyobject_to_timedelta ( PyArray_DatetimeMetaData meta,
PyObject *  obj,
NPY_CASTING  casting,
npy_timedelta out 
)
Converts a PyObject * into a timedelta, in any of the forms supported
If the units metadata isn't known ahead of time, set meta->base to -1, and this function will populate meta with either default values or values from the input object.
The 'casting' parameter is used to control what kinds of inputs are accepted, and what happens. For example, with 'unsafe' casting, unrecognized inputs are converted to 'NaT' instead of throwing an error, while with 'safe' casting an error will be thrown if any precision from the input will be thrown away.
Returns -1 on error, 0 on success.
Convert to an ASCII string for the date parser
Check for a NaT string
Parse as an integer
Use generic units if none was specified
Do no conversion on raw integers
Use the default unit if none was specified
Timedelta scalar
Copy the scalar directly if units weren't specified
Otherwise do a casting transformation
Allow NaT (not-a-time) values to slip through any rule
Timedelta zero-dimensional array
Copy the value directly if units weren't specified
Otherwise do a casting transformation
Allow NaT (not-a-time) values to slip through any rule
Convert from a Python timedelta object
Get the days
Get the seconds
Get the microseconds
Use microseconds if none was specified
Detect the largest unit where every value after is zero, to allow safe casting to seconds if microseconds is zero, for instance.
Switch back to microseconds for the casting operation
With unsafe casting, convert unrecognized objects into NaT and with same_kind casting, convert None into NaT
NPY_NO_EXPORT int convert_pyobjects_to_datetimes ( int  count,
PyObject **  objs,
int *  type_nums,
NPY_CASTING  casting,
npy_int64 *  out_values,
PyArray_DatetimeMetaData inout_meta 
)
Converts an array of PyObject * into datetimes and/or timedeltas, based on the values in type_nums.
If inout_meta->base is -1, uses GCDs to calculate the metadata, filling in 'inout_meta' with the resulting metadata. Otherwise uses the provided 'inout_meta' for all the conversions.
When obj[i] is NULL, out_value[i] will be set to NPY_DATETIME_NAT.
Returns 0 on success, -1 on failure.
No values trivially succeeds
Use the inputs to resolve the unit metadata if requested
Allocate an array of metadata corresponding to the objects
Convert all the objects into timedeltas or datetimes
NULL -> NaT
Merge all the metadatas, starting with the first one
Convert all the values into the resolved unit metadata
Otherwise convert to the provided unit metadata
Convert all the objects into timedeltas or datetimes
NULL -> NaT
Converts a timedelta into a PyObject *.

System Message: WARNING/2 (<string>, line 1); backlink Inline emphasis start-string without end-string.
Not-a-time is returned as the string "NaT". For microseconds or coarser, returns a datetime.timedelta. For units finer than microseconds, returns an integer.
Convert NaT (not-a-time) into None.
If the type's precision is greater than microseconds, is Y/M/B (nonlinear units), or is generic units, return an int
Apply the unit multiplier (TODO: overflow treatment...)
Convert to days/seconds/useconds
'value' represents days, and seconds/useconds are filled.
If it would overflow the datetime.timedelta days, return a raw int
Creates a datetime or timedelta dtype using a copy of the provided metadata.
Create a default datetime or timedelta
Copy the metadata

Referenced by apply_business_day_count(), and business_day_offset().

Creates a datetime or timedelta dtype using the given unit.
NPY_NO_EXPORT PyArrayObject* datetime_arange ( PyObject *  start,
PyObject *  stop,
PyObject *  step,
PyArray_Descr dtype 
)
Implements a datetime-specific arange
Both datetime and timedelta are stored as int64, so they can share value variables.
First normalize the input parameters so there is no Py_None, and start is moved to stop if stop is unspecified.
If start was NULL or None, raise an exception
Step must not be a Datetime
Check if the units of the given dtype are generic, in which case we use the code path that detects the units
If the dtype specified is in generic units, detect the units from the input parameters.
Otherwise use the provided metadata
Set up to convert the objects to a common datetime unit metadata
Convert all the arguments
If no step was provided, default to 1
In the case of arange(datetime, timedelta), convert the timedelta into a datetime by adding the start datetime.
Now start, stop, and step have their values and matching metadata
Calculate the array length
Create the dtype of the result
Create the result array
Extract the data pointer
Create the timedeltas or datetimes
NPY_NO_EXPORT npy_bool datetime_metadata_divides ( PyArray_DatetimeMetaData dividend,
PyArray_DatetimeMetaData divisor,
int  strict_with_nonlinear_units 
)
Determines whether the 'divisor' metadata divides evenly into the 'dividend' metadata.
Any unit can always divide into generic units. In other words, we should be able to convert generic units into any more specific unit.
However, generic units cannot always divide into more specific units. We cannot safely convert datetimes with units back into generic units.
If the bases are different, factor in a conversion
Years and Months are incompatible with all other units (except years and months are compatible with each other).
Could do something complicated here
Could do something complicated here
Could do something complicated here
Take the greater base (unit sizes are decreasing in enum)
Crude, incomplete check for overflow
Both type1 and type2 must be either NPY_DATETIME or NPY_TIMEDELTA. Applies the type promotion rules between the two types, returning the promoted type.
Create a DATETIME or TIMEDELTA dtype
Get the metadata GCD, being strict about nonlinear units for timedelta and relaxed for datetime.

References add_minutes_to_datetimestruct(), and npy_datetimestruct::sec.

Extracts the month number from a 'datetime64[D]' value
Should never get here
static npy_int64 days_to_yearsdays ( npy_int64 *  days_) [static]
Modifies '*days_' to be the day offset within the year, and returns the year.

System Message: WARNING/2 (<string>, line 1); backlink Inline emphasis start-string without end-string.

Docutils System Messages

System Message: ERROR/3 (<string>, line 1); backlink Unknown target name: "days".
Adjust so it's relative to the year 2000 (divisible by 400)
Break down the 400 year cycle to get the year and day within the year
Work out the year/day within the 400 year cycle

References _days_per_month_table, npy_datetimestruct::day, is_leapyear(), npy_datetimestruct::month, and npy_datetimestruct::year.

Referenced by get_datetimestruct_minutes().

NPY_NO_EXPORT PyArray_Descr* find_object_datetime_type ( PyObject *  obj,
int  type_num 
)
Examines all the objects in the given Python object by recursively descending the sequence structure. Returns a datetime or timedelta type with metadata based on the data.
static int find_string_array_datetime64_type ( PyArrayObject arr,
PyArray_DatetimeMetaData meta 
) [static]
Examines all the strings in the given string array, and parses them to find the right metadata.
Returns 0 on success, -1 on failure.
Handle zero-sized arrays specially
Use unsafe casting to allow unicode -> ascii string
Get the resulting string length
Allocate a buffer for strings which fill the buffer completely
The iteration loop
Get the inner loop data/stride/count values
The inner loop
Replicating strnlen with memchr, because Mac OS X lacks it
If the string is all full, use the buffer
Otherwise parse the data in place
Combine it with 'meta'

Referenced by cast_datetime_to_datetime().

NPY_NO_EXPORT void get_datetime_conversion_factor ( PyArray_DatetimeMetaData src_meta,
PyArray_DatetimeMetaData dst_meta,
npy_int64 *  out_num,
npy_int64 *  out_denom 
)
Computes the conversion factor to convert data with 'src_meta' metadata into data with 'dst_meta' metadata.
If overflow occurs, both out_num and out_denom are set to 0, but no error is set.
Generic units change to the destination with no conversion factor
Converting to a generic unit from something other than a generic unit is an error.
Conversions between years/months and other units use the factor averaged over the 400 year leap year cycle.
Year -> Day
Day -> dst_base
Month -> Day
Day -> dst_base
If something overflowed, make both num and denom 0
Swap the numerator and denominator if necessary
Return as a fraction in reduced form
This function returns a pointer to the DateTimeMetaData contained within the provided datetime dtype.

Referenced by cast_datetime_to_datetime().

static npy_uint64 get_datetime_units_factor ( NPY_DATETIMEUNIT  bigbase,
NPY_DATETIMEUNIT  littlebase 
) [static]
Returns the scale factor between the units. Does not validate that bigbase represents larger units than littlebase, or that the units are not generic.
Returns 0 if there is an overflow.
Detect overflow by disallowing the top 16 bits to be 1. That alows a margin of error much bigger than any of the datetime factors.
Calculates the days offset from the 1970 epoch.
Adjust for leap years
1968 is the closest leap year before 1970. Exclude the current year, so add 1.
Add one day for each 4 years
1900 is the closest previous year divisible by 100
Subtract one day for each 100 years
1600 is the closest previous year divisible by 400
Add one day for each 400 years
1972 is the closest later year after 1970. Include the current year, so subtract 2.
Subtract one day for each 4 years
2000 is the closest later year divisible by 100
Add one day for each 100 years
2000 is also the closest later year divisible by 400
Subtract one day for each 400 years
Add the months
Add the days
Calculates the minutes offset from the 1970 epoch.

References _days_per_month_table, days_to_yearsdays(), and is_leapyear().

NPY_NO_EXPORT int get_tzoffset_from_pytzinfo ( PyObject *  timezone_obj,
npy_datetimestruct dts 
)
Gets a tzoffset in minutes by calling the fromutc() function on the Python datetime.tzinfo object.
Create a Python datetime to give to the timezone object
Convert the datetime from UTC to local time
Convert the local datetime into a datetimestruct
Calculate the tzoffset as the difference between the datetimes
Returns true if the datetime metadata matches
For generic units, the num is ignored
Returns true if the object is something that is best considered a Datetime or Timedelta, false otherwise.
static npy_bool is_any_numpy_timedelta ( PyObject *  obj) [static]
Returns true if the object is something that is best considered a Timedelta, false otherwise.
NPY_NO_EXPORT int is_leapyear ( npy_int64  year)
Returns 1 if the given year is a leap year, 0 otherwise.

<

year % 4 == 0

References npy_datetimestruct::year.

Referenced by convert_datetimestruct_utc_to_local(), days_to_yearsdays(), and get_datetimestruct_minutes().

static NPY_GCC_NONNULL ( ) [static]
Returns true if the object is something that is best considered a Datetime, false otherwise.
Imports the PyDateTime functions so we can create these objects. This is called during module initialization
NPY_NO_EXPORT int parse_datetime_extended_unit_from_string ( char *  str,
Py_ssize_t  len,
char *  metastr,
PyArray_DatetimeMetaData out_meta 
)
Converts a substring given by 'str' and 'len' into a date time unit multiplier + enum value, which are populated into out_meta. Other metadata is left along.
'metastr' is only used in the error message, and may be NULL.
Returns 0 on success, -1 on failure.
First comes an optional integer multiplier
Next comes the unit itself, followed by either '/' or the string end
Next comes an optional integer denominator
If the '/' exists, there must be a number followed by ']'
NPY_NO_EXPORT int parse_datetime_metadata_from_metastr ( char *  metastr,
Py_ssize_t  len,
PyArray_DatetimeMetaData out_meta 
)
Parses the metadata string into the metadata C structure.
Returns 0 on success, -1 on failure.
Treat the empty string as generic units
The metadata string must start with a '['
Parse the extended unit inside the []
NPY_NO_EXPORT NPY_DATETIMEUNIT parse_datetime_unit_from_string ( char *  str,
Py_ssize_t  len,
char *  metastr 
)
Converts a substring given by 'str' and 'len' into a date time unit enum value. The 'metastr' parameter is used for error messages, and may be NULL.
Generic units have no representation as a string in this form.
Returns 0 on success, -1 on failure.
Use switch statements so the compiler can make it fast
All the two-letter units are variants of seconds
If nothing matched, it's an error
NPY_NO_EXPORT PyArray_Descr* parse_dtype_from_datetime_typestr ( char *  typestr,
Py_ssize_t  len 
)
Converts a datetype dtype string into a dtype descr object. The "type" string should be NULL-terminated.
First validate that the root is correct, and get the metadata string address
Parse the metadata string into a metadata struct
Create a datetime value from a filled datetime struct and resolution unit. <blockquote> TO BE REMOVED - NOT USED INTERNALLY.</blockquote>

References set_datetimestruct_days().

Fill the datetime struct from the value and resolution unit. <blockquote> TO BE REMOVED - NOT USED INTERNALLY.</blockquote>
Create a timdelta value from a filled timedelta struct and resolution unit. <blockquote> TO BE REMOVED - NOT USED INTERNALLY.</blockquote>

References set_datetimestruct_days().

FIXME: Overflow is not handled at all
To convert from Years or Months, multiplication by the average is done
Fill the timedelta struct from the timedelta value and resolution unit. <blockquote> TO BE REMOVED - NOT USED INTERNALLY.</blockquote>
NPY_NO_EXPORT int raise_if_datetime64_metadata_cast_error ( char *  object_type,
PyArray_DatetimeMetaData src_meta,
PyArray_DatetimeMetaData dst_meta,
NPY_CASTING  casting 
)
Tests whether a datetime64 can be cast from the source metadata to the destination metadata according to the specified casting rule.
Returns -1 if an exception was raised, 0 otherwise.
NPY_NO_EXPORT int raise_if_timedelta64_metadata_cast_error ( char *  object_type,
PyArray_DatetimeMetaData src_meta,
PyArray_DatetimeMetaData dst_meta,
NPY_CASTING  casting 
)
Tests whether a timedelta64 can be cast from the source metadata to the destination metadata according to the specified casting rule.
Returns -1 if an exception was raised, 0 otherwise.

References PyUString_ConcatAndDel, and PyUString_FromString.

static int recursive_find_object_datetime64_type ( PyObject *  obj,
PyArray_DatetimeMetaData meta 
) [static]
Recursively determines the metadata for an NPY_DATETIME dtype.
Returns 0 on success, -1 on failure.
Array -> use its metadata
If the array has metadata, use it
Get the metadata from the type
Combine it with 'meta'
If it's not an object array, stop looking
Datetime scalar -> use its metadata
Combine it with 'meta'
String -> parse it to find out
If it's a value error, clear the error
Otherwise propagate the error
Combine it with 'meta'
Python date object -> 'D'
Combine it with 'meta'
Python datetime object -> 'us'
Combine it with 'meta'
Now check if what we have left is a sequence for recursion
Otherwise ignore it
static int recursive_find_object_timedelta64_type ( PyObject *  obj,
PyArray_DatetimeMetaData meta 
) [static]
Recursively determines the metadata for an NPY_TIMEDELTA dtype.
Returns 0 on success, -1 on failure.
Array -> use its metadata
If the array has metadata, use it
Get the metadata from the type
Combine it with 'meta'
If it's not an object array, stop looking
Datetime scalar -> use its metadata
Combine it with 'meta'
String -> parse it to find out
No timedelta parser yet
Python timedelta object -> 'us'
Combine it with 'meta'
Now check if what we have left is a sequence for recursion
Otherwise ignore it
static void set_datetimestruct_days ( npy_int64  days,
npy_datetimestruct dts 
) [static]
Fills in the year, month, day in 'dts' based on the days offset from 1970.

Referenced by PyArray_DatetimeStructToDatetime(), and PyArray_TimedeltaStructToTimedelta().


Variable Documentation

npy_uint32 _datetime_factors[] [static]
Initial value:
 {
    1,  
    1,  
    7,  
    1,  
    24, 
    60, 
    60, 
    1000,
    1000,
    1000,
    1000,
    1000,
    1000,
    1,   
    0    
}
Lookup table for factors between datetime units, except for years and months.
Initial value:
 {
    "Y",
    "M",
    "W",
    "<invalid>",
    "D",
    "h",
    "m",
    "s",
    "ms",
    "us",
    "ns",
    "ps",
    "fs",
    "as",
    "generic"
}
Exported as DATETIMEUNITS in multiarraymodule.c

Referenced by parse_iso_8601_datetime().

Initial value:
 {
    { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
    { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
}
Days per month, regular year and leap year

Referenced by days_to_yearsdays(), and get_datetimestruct_minutes().

Initial value:
 {
    {12, 52, 365},                            
    {NPY_FR_M, NPY_FR_W, NPY_FR_D},
    {4,  30, 720},                            
    {NPY_FR_W, NPY_FR_D, NPY_FR_h},
    {7,  168, 10080},                         
    {NPY_FR_D, NPY_FR_h, NPY_FR_m},
    {0},                                      
    {0},
    {24, 1440, 86400},                        
    {NPY_FR_h, NPY_FR_m, NPY_FR_s},
    {60, 3600},                               
    {NPY_FR_m, NPY_FR_s},
    {60, 60000},                              
    {NPY_FR_s, NPY_FR_ms},
    {1000, 1000000},                          
    {0, 0}
}