Sirish Kumar Bethala
Sirish Kumar Bethala

Reputation: 9269

Python Datetime issue

I am trying to calculate the difference between two different time stamps mentioned below. I am getting a value of 25324 seconds which is less than the actual difference . What is the issue here ?

from datetime import datetime

time_format = "%Y-%m-%d %H:%M:%S"

d1 = datetime.strptime('2013-12-12 03:59:33', time_format)
d2 = datetime.strptime('2013-12-09 20:57:29', time_format)
print (d1 - d2).seconds

25324

Upvotes: 0

Views: 57

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31270

A timedelta object contains the time in days, seconds and microseconds. You have to add them together to get the full number.

from datetime import datetime

time_format = "%Y-%m-%d %H:%M:%S"

d1 = datetime.strptime('2013-12-12 03:59:33', time_format)
d2 = datetime.strptime('2013-12-09 20:57:29', time_format)

diff  = d1 - d2
print diff  # 2 days, 7:02:04
print diff.days * 24 * 60 * 60 + diff.seconds  # 198124

The method total_seconds() does that automatically.

The point is you can't store a number that might need accuracy over the range from 999999999 days to 1 microsecond simultaneously in a single float, so it's split into three integers.

Upvotes: 5

Related Questions