Python date and time subtraction - wrong results?
5 answers
timedelta.seconds
is not the total number of seconds, but the rest in seconds after the days have been counted. Using your example:
>>> import datetime
>>> (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16))
datetime.timedelta(1, 2098)
Which datetime.timedelta(1, 2098)
means your timedelta is 1 day, plus 2098 seconds.
What you want is something like:
>>> delta = (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16))
>>> (delta.days * 86400) + delta.seconds
88498
+1
source to share
Interestingly, there is no total_seconds yet . It works for both python2 and python3. And this is the easiest way to get the total number of seconds timedelta.
In your case
In [5]: (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,1
...: 6)).seconds
Out[5]: 2098
In [6]: (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,1
...: 6)).total_seconds()
Out[6]: 88498.0
Another example:
In [1]: from datetime import datetime
In [2]: d1 = datetime(2018,1,1)
In [3]: d2 = datetime(2018,1,3)
In [4]: td = d2 - d1
In [5]: td.seconds
Out[5]: 0
In [6]: td.days
Out[6]: 2
In [7]: td.total_seconds()
Out[7]: 172800.0
+1
source to share