[Python-Dev] datetime +/- scalars (int, long, float)?
Neal Norwitz
neal@metaslash.com
Sun, 03 Mar 2002 09:29:01 -0500
Would it be good to allow adding/subtracting scalars (int, long, float)
to/from date/times? The scalar value would be # of seconds.
So:
dt = datetime() # some date/time
dt + 5 # would add 5 seconds
dt + 5.3 # would add 5 seconds 300000 usecs
If so, attached is a patch.
Neal
--
Index: sandbox/datetime/datetime.py
===================================================================
RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v
retrieving revision 1.22
diff -w -u -r1.22 datetime.py
--- sandbox/datetime/datetime.py 3 Mar 2002 06:11:54 -0000 1.22
+++ sandbox/datetime/datetime.py 3 Mar 2002 14:26:19 -0000
@@ -590,6 +590,13 @@
result.__microsecond = us
result.__tzoffset = self.__tzoffset
return result
+ elif isinstance(other, (int, long)):
+ return self + timedelta(0, other)
+ elif isinstance(other, float):
+ # XXX not sure if float needs it's own condition or
+ # XXX should work the same as int/long
+ ss, us = divmod(other, 1000000)
+ return self + timedelta(0, ss, int(us))
return NotImplemented
__radd__ = __add__
@@ -598,6 +605,13 @@
"Subtract two datetimes, or a datetime and a timedelta."
if isinstance(other, timedelta):
return self + -other
+ elif isinstance(other, (int, long)):
+ return self + -timedelta(0, other)
+ elif isinstance(other, float):
+ # XXX not sure if float needs it's own condition or
+ # XXX should work the same as int/long
+ ss, us = divmod(other, 1000000)
+ return self + -timedelta(0, ss, int(us))
if isinstance(other, datetime):
days1 = self.toordinal()
days2 = other.toordinal()