324

I have a time difference

import time
import datetime

time1 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
...
time2 = datetime.datetime.fromtimestamp(time.mktime(time.gmtime()))
diff = time2 - time1

Now, how do I find the total number of seconds that passed? diff.seconds doesn't count days. I could do:

diff.seconds + diff.days * 24 * 3600

Is there a built-in method for this?

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 11
    @RestRisiko - you're right. Still, it's useful to have the question on Stack Overflow, so the next time me, or someone else, Googles for it, he has a good answer as the top result. – ripper234 Apr 02 '11 at 08:33
  • We can discuss alternative definitions of "good" later; please read my answer before you run away :) – John Machin Apr 02 '11 at 10:02
  • There are multiple issues with computing `time1`, and `diff` in your code. To get the current utc time as a naive datetime object, use `datetime.utcnow()` instead. To understand why you should use UTC instead of the local time to find the difference see [Find if 24 hrs have passed between datetimes - Python](http://stackoverflow.com/a/26313848/4279). `time.monotonic()` could be preferable to find elapsed time between events (instead of `time.time()` or `datetime.utcnow()`). – jfs Jan 19 '15 at 20:50

5 Answers5

607

Use timedelta.total_seconds().

>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0
  • 7
    If somebody still needs to be compatible with 2.6: See http://stackoverflow.com/questions/3318348/how-can-i-extend-pythons-datetime-datetime-with-my-own-methods/14214646#14214646 for how to extend datetime.timedelta with the new method yourself. – Uwe Geuder Dec 16 '13 at 18:42
  • 11
    datetime.timedelta.total_seconds(time2-time1) in Python3.6 – Russo May 23 '18 at 16:05
  • 4
    `(time2-time1).total_seconds()` in python 3 – taras Nov 04 '21 at 10:35
12

You have a problem one way or the other with your datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) expression.

(1) If all you need is the difference between two instants in seconds, the very simple time.time() does the job.

(2) If you are using those timestamps for other purposes, you need to consider what you are doing, because the result has a big smell all over it:

gmtime() returns a time tuple in UTC but mktime() expects a time tuple in local time.

I'm in Melbourne, Australia where the standard TZ is UTC+10, but daylight saving is still in force until tomorrow morning so it's UTC+11. When I executed the following, it was 2011-04-02T20:31 local time here ... UTC was 2011-04-02T09:31

>>> import time, datetime
>>> t1 = time.gmtime()
>>> t2 = time.mktime(t1)
>>> t3 = datetime.datetime.fromtimestamp(t2)
>>> print t0
1301735358.78
>>> print t1
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=9, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=0) ### this is UTC
>>> print t2
1301700663.0
>>> print t3
2011-04-02 10:31:03 ### this is UTC+1
>>> tt = time.time(); print tt
1301736663.88
>>> print datetime.datetime.now()
2011-04-02 20:31:03.882000 ### UTC+11, my local time
>>> print datetime.datetime(1970,1,1) + datetime.timedelta(seconds=tt)
2011-04-02 09:31:03.880000 ### UTC
>>> print time.localtime()
time.struct_time(tm_year=2011, tm_mon=4, tm_mday=2, tm_hour=20, tm_min=31, tm_sec=3, tm_wday=5, tm_yday=92, tm_isdst=1) ### UTC+11, my local time

You'll notice that t3, the result of your expression is UTC+1, which appears to be UTC + (my local DST difference) ... not very meaningful. You should consider using datetime.datetime.utcnow() which won't jump by an hour when DST goes on/off and may give you more precision than time.time()

John Machin
  • 81,303
  • 11
  • 141
  • 189
  • Thanks for the clarification. For the purpose I'm using right now, a difference of even a few hours every now and then isn't important, but I'll be sure to check this out in the future when I write something more meaningful. – ripper234 Apr 02 '11 at 12:24
0

More compact way to get the difference between two datetime objects and then convert the difference into seconds is shown below (Python 3x):

from datetime import datetime
        
time1 = datetime.strftime('18 01 2021', '%d %m %Y')
    
time2 = datetime.strftime('19 01 2021', '%d %m %Y')

difference = time2 - time1

difference_in_seconds = difference.total_seconds()
Atif Bashir
  • 319
  • 4
  • 13
0

You also can divide a timedelta by another timedelta for a specific unit. As the documentation states:

timedelta.total_seconds()

Return the total number of seconds contained in the duration. Equivalent to td / timedelta(seconds=1). For interval units other than seconds, use the division form directly (e.g. td / timedelta(microseconds=1)).

ericbn
  • 10,163
  • 3
  • 47
  • 55
-7

You can use mx.DateTime module

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79