numpy  2.0.0
src/multiarray/_datetime.h File Reference

Go to the source code of this file.

Functions

NPY_NO_EXPORT void numpy_pydatetime_import ()
NPY_NO_EXPORT int is_leapyear (npy_int64 year)
NPY_NO_EXPORT npy_int64 get_datetimestruct_days (const npy_datetimestruct *dts)
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 PyArray_Descrdatetime_type_promotion (PyArray_Descr *type1, PyArray_Descr *type2)
NPY_NO_EXPORT int convert_datetimestruct_to_datetime (PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts, npy_datetime *out)
NPY_NO_EXPORT int days_to_month_number (npy_datetime days)
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 NPY_DATETIMEUNIT parse_datetime_unit_from_string (char *str, Py_ssize_t len, char *metastr)
NPY_NO_EXPORT int convert_datetime_divisor_to_multiple (PyArray_DatetimeMetaData *meta, int den, char *metastr)
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_datetime64_metadata (PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, 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_timedelta64_metadata (PyArray_DatetimeMetaData *src_meta, PyArray_DatetimeMetaData *dst_meta, NPY_CASTING casting)
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 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 get_tzoffset_from_pytzinfo (PyObject *timezone, npy_datetimestruct *dts)
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 int convert_pydatetime_to_datetimestruct (PyObject *obj, npy_datetimestruct *out, NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo)
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 int convert_datetime_to_datetimestruct (PyArray_DatetimeMetaData *meta, npy_datetime dt, npy_datetimestruct *out)
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 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)
NPY_NO_EXPORT npy_bool is_any_numpy_datetime_or_timedelta (PyObject *obj)
NPY_NO_EXPORT PyArrayObjectdatetime_arange (PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *dtype)
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]

Function Documentation

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

References PyArray_DatetimeMetaData::base, and NPY_FR_GENERIC.

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

References convert_pydatetime_to_datetimestruct(), npy_datetimestruct::day, get_datetimestruct_minutes(), npy_datetimestruct::hour, npy_datetimestruct::min, npy_datetimestruct::month, and npy_datetimestruct::year.

Referenced by can_cast_timedelta64_units().

This provides the casting rules for the DATETIME data type metadata.

References NPY_FR_D, NPY_FR_h, NPY_FR_M, NPY_FR_m, NPY_FR_W, and NPY_FR_Y.

This provides the casting rules for the DATETIME data type units.
Notably, there is a barrier between 'date units' and 'time units' for all but 'unsafe' casting.
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

Referenced by parse_iso_8601_datetime().

This provides the casting rules for the TIMEDELTA data type metadata.

Referenced by PyArray_CanCastTo().

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

References append_metastr_to_string(), PyUString_ConcatAndDel, and PyUString_FromString.

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_Check, PyArray_DESCR, PyArray_IsScalar, 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 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.
Returns 0 on success, -1 on failure.
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.
For days or coarser, returns a datetime.date. For microseconds or coarser, returns a datetime.datetime. For units finer than microseconds, returns an integer.
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.
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

Referenced by _strided_to_strided_datetime_general_cast(), and convert_pydatetime_to_datetimestruct().

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.

'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.
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
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'

References PyArray_DatetimeMetaData::base, convert_datetimestruct_to_datetime(), convert_pydatetime_to_datetimestruct(), NPY_FR_D, PyArray_DatetimeMetaData::num, and raise_if_datetime64_metadata_cast_error().

Referenced by append_metastr_to_string(), and convert_pydatetime_to_datetimestruct().

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
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
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.
Generic units divide into anything
Non-generic units never divide 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 npy_datetimestruct::sec.

Extracts the month number, within the current year, from a 'datetime64[D]' value. January is 1, etc.
Extracts the month number from a 'datetime64[D]' value
Should never get here
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.
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(), and PyArray_CanCastTo().

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
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

Referenced by PyArray_Correlate().

Returns true if the object is something that is best considered a Datetime or 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 days_to_yearsdays(), and get_datetimestruct_minutes().

Imports the PyDateTime functions so we can create these objects. This is called during module initialization
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.
Returns 0 on success, -1 on failure.
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

References npy_datetimestruct::month, and npy_datetimestruct::year.

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, and len should contain its string length.
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

Variable Documentation