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 time
| 571 | |
| 572 | |
| 573 | class timedelta: |
| 574 | """Represent the difference between two datetime objects. |
| 575 | |
| 576 | Supported operators: |
| 577 | |
| 578 | - add, subtract timedelta |
| 579 | - unary plus, minus, abs |
| 580 | - compare to timedelta |
| 581 | - multiply, divide by int |
| 582 | |
| 583 | In addition, datetime supports subtraction of two datetime objects |
| 584 | returning a timedelta, and addition or subtraction of a datetime |
| 585 | and a timedelta giving a datetime. |
| 586 | |
| 587 | Representation: (days, seconds, microseconds). Why? Because I |
| 588 | felt like it. |
| 589 | """ |
| 590 | __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' |
| 591 | |
| 592 | def __new__(cls, days=0, seconds=0, microseconds=0, |
| 593 | milliseconds=0, minutes=0, hours=0, weeks=0): |
| 594 | # Doing this efficiently and accurately in C is going to be difficult |
| 595 | # and error-prone, due to ubiquitous overflow possibilities, and that |
| 596 | # C double doesn't have enough bits of precision to represent |
| 597 | # microseconds over 10K years faithfully. The code here tries to make |
| 598 | # explicit where go-fast assumptions can be relied on, in order to |
| 599 | # guide the C implementation; it's way more convoluted than speed- |
| 600 | # ignoring auto-overflow-to-long idiomatic Python could be. |
| 601 | |
| 602 | # XXX Check that all inputs are ints or floats. |
| 603 | |
| 604 | # Final values, all integer. |
| 605 | # s and us fit in 32-bit signed ints; d isn't bounded. |
| 606 | d = s = us = 0 |
| 607 | |
| 608 | # Normalize everything to days, seconds, microseconds. |
| 609 | days += weeks*7 |
| 610 | seconds += minutes*60 + hours*3600 |
| 611 | microseconds += milliseconds*1000 |
| 612 | |
| 613 | # Get rid of all fractions, and normalize s and us. |
| 614 | # Take a deep breath <wink>. |
| 615 | if isinstance(days, float): |
| 616 | dayfrac, days = _math.modf(days) |
| 617 | daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.)) |
| 618 | assert daysecondswhole == int(daysecondswhole) # can't overflow |
| 619 | s = int(daysecondswhole) |
| 620 | assert days == int(days) |
| 621 | d = int(days) |
| 622 | else: |
| 623 | daysecondsfrac = 0.0 |
| 624 | d = days |
| 625 | assert isinstance(daysecondsfrac, float) |
| 626 | assert abs(daysecondsfrac) <= 1.0 |
| 627 | assert isinstance(d, int) |
| 628 | assert abs(s) <= 24 * 3600 |
| 629 | # days isn't referenced again before redefinition |
| 630 |
no outgoing calls
no test coverage detected