3
date1 = datetime.datetime(2012, 10, 10, 10, 15, 44)
date2 = datetime.datetime(2012, 10, 17, 8, 45, 38)
roundedA = date2.replace(second = 0, microsecond = 0)
print roundedA
roundedB = date1.replace(second = 0, microsecond = 0)
print roundedB
minutes = (roundedA - roundedB).min
print minutes

Result is:

-999999999 days, 0:00:00

I want to count 2 different dates differences. I subtracted above, but it does not give me what I want. How to do subtract two dates and get the result in minutes or hours.

DSM
  • 319,184
  • 61
  • 566
  • 472
John Smith
  • 2,496
  • 7
  • 27
  • 34

2 Answers2

5

The timedelta.min attribute does not represent minutes- it means the smallest possible timedelta (see here). If you want to get it in minutes, you can do:

d = roundedA - roundedB
minutes = d.days * 1440 + d.seconds / 60

This is because only seconds and days are stored internally in timedelta.

David Robinson
  • 74,512
  • 15
  • 159
  • 179
1

You can use also time module to get result of subtraction in seconds:

import time
import datetime
date1 = datetime.datetime(2012, 10, 10, 10, 15, 44)
date2 = datetime.datetime(2012, 10, 17, 8, 45, 38)
var1 = time.mktime(date1.timetuple())
var2 = time.mktime(date2.timetuple())
result_in_seconds = var2 - var1

>>> var2 - var1
599394.0

Or use function provided in answer

>>> def days_hours_minutes(td):
...     return td.days, td.seconds//3600, (td.seconds//60)%60
... 
>>> date2 - date1
datetime.timedelta(6, 80994)
>>> days_hours_minutes(datetime.timedelta(6, 80994))
(6, 22, 29)
Community
  • 1
  • 1
insider
  • 1,718
  • 1
  • 16
  • 15