diff options
author | Gerhard Weis <gerhard.weis@gmail.com> | 2013-01-25 14:53:07 +1000 |
---|---|---|
committer | Gerhard Weis <gerhard.weis@gmail.com> | 2013-01-25 14:53:07 +1000 |
commit | 024882df877f9d0dc05c2b88224d0c8d39bf7190 (patch) | |
tree | cc88eaa4d02507211dd7fe5572b8e824c67ec541 | |
parent | f71adda7aec3298f1194e9376d2fa681eb496b8d (diff) | |
download | isodate-024882df877f9d0dc05c2b88224d0c8d39bf7190.tar.gz |
make sure months and years are Decimal
use floor divmod with Decimal instances.
closes #5
-rw-r--r-- | src/isodate/duration.py | 15 |
1 files changed, 14 insertions, 1 deletions
diff --git a/src/isodate/duration.py b/src/isodate/duration.py index 12c0df4..4484919 100644 --- a/src/isodate/duration.py +++ b/src/isodate/duration.py @@ -31,13 +31,22 @@ The class Duration allows to define durations in years and months and can be used as limited replacement for timedelta objects. ''' from datetime import date, datetime, timedelta +from decimal import Decimal, ROUND_FLOOR def fquotmod(val, low, high): ''' A divmod function with boundaries. + ''' - div, mod = divmod(val - low, high - low) + # assumes that all the maths is done with Decimals. + # divmod for Decimal uses truncate instead of floor as builtin divmod, so we have + # to do it manually here. + a, b = val - low, high - low + div = (a / b).to_integral(ROUND_FLOOR) + mod = a - div * b + # if we were not usig Decimal, it would look like this. + #div, mod = divmod(val - low, high - low) mod += low return int(div), mod @@ -83,6 +92,10 @@ class Duration(object): ''' Initialise this Duration instance with the given parameters. ''' + if not isinstance(months, Decimal): + months = Decimal(str(months)) + if not isinstance(years, Decimal): + years = Decimal(str(years)) self.months = months self.years = years self.tdelta = timedelta(days, seconds, microseconds, milliseconds, |