Difference between two dates in seconds

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Thu Sep 28 01:20:59 CEST 2006

On Wed, 27 Sep 2006 20:16:52 +0200, Fredrik Lundh wrote:

> Claes at work wrote:
>> Please tell me there is a simpler way than subtracting two datetimes
>> to get a timedelta and then compute
>> days * number of seconds per day + seconds
>> from it myself??
> why would you have to do that yourself?  why not let Python do it for 
> you?  here's the code:
>     seconds = td.days * 86400 + td.seconds

I'm sure somebody as experienced as Fredrik doesn't need to be told why
peppering code with magic constants like 84600 are a less than ideal
solution -- and for those who do need to be told, carefully compare what I
wrote to what Fredrik wrote to see one of those reasons.

Arguably a better solution would be to do this:

seconds = td.days * 24*60*60 + td.seconds

Still not ideal though, although that depends on just how often you need
to convert days to or from seconds.


More information about the Python-list mailing list