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