I don't quite understand how negative arguments in datetime.timedelta
are interpreted.
With Positive values:
>>> from datetime import timedelta
>>> d = timedelta(days=1,seconds=1,microseconds=1,milliseconds=1,minutes=1,hours=1,weeks=1)
>>> (d.days, d.seconds, d.microseconds)
>>> (8, 3661, 1001)
This is pretty straightforward. A similar example with negative values looks like:
>>> from datetime import timedelta
>>> d = timedelta(days=-1,seconds=-1,microseconds=-1,milliseconds=-1,minutes=-1,hours=-1,weeks=-1)
>>> (d.days, d.seconds, d.microseconds)
>>> (-9, 82738, 998999)
As per my understanding seconds and microseconds are derived like:
86399 - (-60-3600-1)
999999 - (-1-1000)
Is this correct? How come days equals -9?
I am reading this section of docs. But still don't quite understand the working with negative values. Please share explanations or relevant documentation links. Thanks :)
They can be both positive and negative. Timedelta is a subclass of datetime.
In timedelta() object delta represents the difference between two dates or times. All the arguments are optional and are 0 by default. We can pass both positive and negative values in the arguments.
timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
You can also find the difference between two datetime objects to get a timedelta object and perform the comparison based on the positive or negative value returned by the timedelta. total_seconds() function. if seconds < 0: print('First date is less than the second date.
Because of the way timedeltas are stored internally, only the days
attribute can take on negative values. This can be surprising when the timedelta is printed back. An illuminating example from the docs,
>>> d = timedelta(microseconds=-1)
>>> (d.days, d.seconds, d.microseconds)
(-1, 86399, 999999)
ie. -1d + 86399s + 999999µs = -1µs
It makes complete sense, (-1 week + -1 day) + (-1 hours) + (-1 minutes) + (-1 seconds) + (-1 milliseconds) + (-1 microseconds)
equals to: (-8 days) + (-1 hours) + (-1 minutes) + (-1 seconds) + (-1 milliseconds) + (-1 microseconds)
By having less than -8 days, with -1 hours, -1 minutes, ... the number of days will have to be even less than -8 to make the negative hours, minutes, seconds... into positive hours, minutes, seconds....(since only days can be represented negatively, others,such as seconds, are always represented positively). Which means that days will have to be -9.
If you print d
, you will get -9 days 22:58:58.998999
, with negative 9 days and positive 22+ hours. Seeing the str
of the timedelta
could help you have better understanding of how negative timedelta
is represented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With