Python datetime subtraction - wrong results?
I must be doing something wrong here, any ideas?
>开发者_JAVA技巧;>> (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)).seconds
2098
It should be getting more than that many seconds.
timedelta.seconds
gives you the seconds
field of the timedelta. But it also has a days
field (and a milliseconds
field).
So you would want something like
delta = datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)
delta.seconds + delta.days*86400
It's actually returning a timedelta which has a day field also i.e.
c.seconds = 2098
but
c.days = 1
I wonder that there's still no total_seconds example. It works for both python2 and python3. And it's the easiest way to get timedelta total seconds count.
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
timedelta.seconds
isn't the total number of seconds, it's the remainder in seconds after days have been accounted for. 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)
That datetime.timedelta(1, 2098)
means that 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
datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)
returns a datetime.timedelta
object which has a days
attribute. The difference that you are calculating is actually 1 day and 2098 seconds.
精彩评论