Represent the difference between two datetime objects. Supported operators: - add, subtract timedelta - unary plus, minus, abs - compare to timedelta - multiply, divide by int In addition, datetime supports subtraction of two datetime objects returning a timedelta, and
| 613 | |
| 614 | |
| 615 | class timedelta: |
| 616 | """Represent the difference between two datetime objects. |
| 617 | |
| 618 | Supported operators: |
| 619 | |
| 620 | - add, subtract timedelta |
| 621 | - unary plus, minus, abs |
| 622 | - compare to timedelta |
| 623 | - multiply, divide by int |
| 624 | |
| 625 | In addition, datetime supports subtraction of two datetime objects |
| 626 | returning a timedelta, and addition or subtraction of a datetime |
| 627 | and a timedelta giving a datetime. |
| 628 | |
| 629 | Representation: (days, seconds, microseconds). |
| 630 | """ |
| 631 | # The representation of (days, seconds, microseconds) was chosen |
| 632 | # arbitrarily; the exact rationale originally specified in the docstring |
| 633 | # was "Because I felt like it." |
| 634 | |
| 635 | __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' |
| 636 | |
| 637 | def __new__(cls, days=0, seconds=0, microseconds=0, |
| 638 | milliseconds=0, minutes=0, hours=0, weeks=0): |
| 639 | # Doing this efficiently and accurately in C is going to be difficult |
| 640 | # and error-prone, due to ubiquitous overflow possibilities, and that |
| 641 | # C double doesn't have enough bits of precision to represent |
| 642 | # microseconds over 10K years faithfully. The code here tries to make |
| 643 | # explicit where go-fast assumptions can be relied on, in order to |
| 644 | # guide the C implementation; it's way more convoluted than speed- |
| 645 | # ignoring auto-overflow-to-long idiomatic Python could be. |
| 646 | |
| 647 | for name, value in ( |
| 648 | ("days", days), |
| 649 | ("seconds", seconds), |
| 650 | ("microseconds", microseconds), |
| 651 | ("milliseconds", milliseconds), |
| 652 | ("minutes", minutes), |
| 653 | ("hours", hours), |
| 654 | ("weeks", weeks) |
| 655 | ): |
| 656 | if not isinstance(value, (int, float)): |
| 657 | raise TypeError( |
| 658 | f"unsupported type for timedelta {name} component: {type(value).__name__}" |
| 659 | ) |
| 660 | |
| 661 | # Final values, all integer. |
| 662 | # s and us fit in 32-bit signed ints; d isn't bounded. |
| 663 | d = s = us = 0 |
| 664 | |
| 665 | # Normalize everything to days, seconds, microseconds. |
| 666 | days += weeks*7 |
| 667 | seconds += minutes*60 + hours*3600 |
| 668 | microseconds += milliseconds*1000 |
| 669 | |
| 670 | # Get rid of all fractions, and normalize s and us. |
| 671 | # Take a deep breath <wink>. |
| 672 | if isinstance(days, float): |
no outgoing calls