catisgar
catisgar

Reputation: 31

odd datetime difference in Python

Could someone tell me how come python shows a difference of 1310 seconds between two dates?

import datetime
time1=datetime.datetime(2016,12,8,20,5,0)
time2=datetime.datetime(2016,12,7,19,43,10)
timediff=time1-time2
print(timediff)
print(timediff.seconds)

>1 day, 0:21:50
>1310

Upvotes: 3

Views: 374

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

As you can read here a timedelta object has three fields: days; seconds; and microseconds. Or as is specified in the documentation:

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

(...)

Only days, seconds and microseconds are stored internally. Arguments are converted to those units:

  • A millisecond is converted to 1000 microseconds.
  • A minute is converted to 60 seconds.
  • An hour is converted to 3600 seconds.
  • A week is converted to 7 days.

(formatting added)

Althout the constructor is timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) and thus provides ways to enter hours, it thus converts the minutes, hours, etc. all to seconds. The constructor will look like:

def __init__(self, days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0):
    self.microseconds = microseconds+1000*milliseconds
    self.seconds = seconds+60*minutes+3600*hours+self.microseconds//1000000
    self.microseconds %= 1000000
    self.days = days+7*weeks+self.seconds//86400
    self.seconds %= 86400

(but probably a bit more advanced, etc.)

So that means that .seconds actually is modulo day, and without microseconds.

You can however use timediff.total_seconds to return the total amount of seconds:

>>> timediff.total_seconds()
87710.0

So total_seconds() is basically:

def total_seconds(self):
    return 86400.0*self.days+self.seconds+1e-6*self.microseconds
    #      ^ number of seconds in a day   ^
    #                                     | 1 micro is 1e-6

If you divide your 1310 by 60, you will see that it returns:

>>> 1310/60 # obtain number of minutes
21.833333333333332
>>> 1310%60 # obtain number of seconds  (without minutes)
50

so 21 minutes and 50 seconds

Upvotes: 6

Related Questions