MCPcopy Create free account
hub / github.com/numpy/numpy / convert_pyobject_to_timedelta

Function convert_pyobject_to_timedelta

numpy/core/src/multiarray/datetime.c:2568–2833  ·  view source on GitHub ↗

* 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, * unre

Source from the content-addressed store, hash-verified

2566 * Returns -1 on error, 0 on success.
2567 */
2568NPY_NO_EXPORT int
2569convert_pyobject_to_timedelta(PyArray_DatetimeMetaData *meta, PyObject *obj,
2570 NPY_CASTING casting, npy_timedelta *out)
2571{
2572 if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
2573 PyObject *utf8 = NULL;
2574 int succeeded = 0;
2575
2576 /* Convert to an UTF8 string for the date parser */
2577 if (PyBytes_Check(obj)) {
2578 utf8 = PyUnicode_FromEncodedObject(obj, NULL, NULL);
2579 if (utf8 == NULL) {
2580 return -1;
2581 }
2582 }
2583 else {
2584 utf8 = obj;
2585 Py_INCREF(utf8);
2586 }
2587
2588 Py_ssize_t len = 0;
2589 char const *str = PyUnicode_AsUTF8AndSize(utf8, &len);
2590 if (str == NULL) {
2591 Py_DECREF(utf8);
2592 return -1;
2593 }
2594
2595 /* Check for a NaT string */
2596 if (len <= 0 || (len == 3 &&
2597 tolower(str[0]) == 'n' &&
2598 tolower(str[1]) == 'a' &&
2599 tolower(str[2]) == 't')) {
2600 *out = NPY_DATETIME_NAT;
2601 succeeded = 1;
2602 }
2603 /* Parse as an integer */
2604 else {
2605 char *strend = NULL;
2606
2607 *out = strtol(str, &strend, 10);
2608 if (strend - str == len) {
2609 succeeded = 1;
2610 }
2611 }
2612 Py_DECREF(utf8);
2613
2614 if (succeeded) {
2615 /* Use generic units if none was specified */
2616 if (meta->base == NPY_FR_ERROR) {
2617 meta->base = NPY_FR_GENERIC;
2618 meta->num = 1;
2619 }
2620
2621 return 0;
2622 }
2623 }
2624 /* Do no conversion on raw integers */
2625 else if (PyLong_Check(obj)) {

Callers 1

Calls 6

PyArray_NDIMFunction · 0.85
PyArray_DESCRFunction · 0.85
PyArray_DATAFunction · 0.85

Tested by

no test coverage detected