|
1 | 1 | # -*- coding: utf-8 -*-
|
2 | 2 | # cython: profile=False
|
3 | 3 | import collections
|
| 4 | +import re |
4 | 5 |
|
5 | 6 | import sys
|
6 | 7 | cdef bint PY3 = (sys.version_info[0] >= 3)
|
@@ -506,6 +507,57 @@ def _binary_op_method_timedeltalike(op, name):
|
506 | 507 | # ----------------------------------------------------------------------
|
507 | 508 | # Timedelta Construction
|
508 | 509 |
|
| 510 | +iso_pater = re.compile(r"""P |
| 511 | + (?P<days>-?[0-9]*)DT |
| 512 | + (?P<hours>[0-9]{1,2})H |
| 513 | + (?P<minutes>[0-9]{1,2})M |
| 514 | + (?P<seconds>[0-9]{0,2}) |
| 515 | + (\. |
| 516 | + (?P<milliseconds>[0-9]{1,3}) |
| 517 | + (?P<microseconds>[0-9]{0,3}) |
| 518 | + (?P<nanoseconds>[0-9]{0,3}) |
| 519 | + )?S""", re.VERBOSE) |
| 520 | + |
| 521 | + |
| 522 | +cdef int64_t parse_iso_format_string(object iso_fmt) except? -1: |
| 523 | + """ |
| 524 | + Extracts and cleanses the appropriate values from a match object with |
| 525 | + groups for each component of an ISO 8601 duration |
| 526 | +
|
| 527 | + Parameters |
| 528 | + ---------- |
| 529 | + iso_fmt: |
| 530 | + ISO 8601 Duration formatted string |
| 531 | +
|
| 532 | + Returns |
| 533 | + ------- |
| 534 | + ns: int64_t |
| 535 | + Precision in nanoseconds of matched ISO 8601 duration |
| 536 | +
|
| 537 | + Raises |
| 538 | + ------ |
| 539 | + ValueError |
| 540 | + If ``iso_fmt`` cannot be parsed |
| 541 | + """ |
| 542 | + |
| 543 | + cdef int64_t ns = 0 |
| 544 | + |
| 545 | + match = re.match(iso_pater, iso_fmt) |
| 546 | + if match: |
| 547 | + match_dict = match.groupdict(default='0') |
| 548 | + for comp in ['milliseconds', 'microseconds', 'nanoseconds']: |
| 549 | + match_dict[comp] = '{:0<3}'.format(match_dict[comp]) |
| 550 | + |
| 551 | + for k, v in match_dict.items(): |
| 552 | + ns += timedelta_from_spec(v, '0', k) |
| 553 | + |
| 554 | + else: |
| 555 | + raise ValueError("Invalid ISO 8601 Duration format - " |
| 556 | + "{}".format(iso_fmt)) |
| 557 | + |
| 558 | + return ns |
| 559 | + |
| 560 | + |
509 | 561 | cdef _to_py_int_float(v):
|
510 | 562 | # Note: This used to be defined inside Timedelta.__new__
|
511 | 563 | # but cython will not allow `cdef` functions to be defined dynamically.
|
@@ -825,7 +877,11 @@ class Timedelta(_Timedelta):
|
825 | 877 | if isinstance(value, Timedelta):
|
826 | 878 | value = value.value
|
827 | 879 | elif is_string_object(value):
|
828 |
| - value = np.timedelta64(parse_timedelta_string(value)) |
| 880 | + if len(value) > 0 and value[0] == 'P': |
| 881 | + value = parse_iso_format_string(value) |
| 882 | + else: |
| 883 | + value = parse_timedelta_string(value) |
| 884 | + value = np.timedelta64(value) |
829 | 885 | elif PyDelta_Check(value):
|
830 | 886 | value = convert_to_timedelta64(value, 'ns')
|
831 | 887 | elif is_timedelta64_object(value):
|
|
0 commit comments