Python date and time subtraction - wrong results?

I must be doing something wrong here, any ideas?

>>> (datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)).seconds
2098

      

It should take more than many seconds.

+2


source to share


5 answers


timedelta.seconds

gives a seconds

timedelta field . But it also has a field days

(and a field milliseconds

).

So, you need something like



delta = datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)
delta.seconds + delta.days*86400

      

+10


source


It actually returns a timedelta that has a day field, etc.

c.seconds = 2098



but

c.days = 1

+2


source


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


datetime.datetime(2008,11,7,10,5,14)-datetime.datetime(2008,11,6,9,30,16)

returns an object datetime.timedelta

that has an attribute days

. The difference you are calculating is actually 1 day and 2098 seconds.

+1


source


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







All Articles