34

I have taken two dates as

import datetime
data1 = datetime.datetime.now()
data2 = datetime.datetime.now()

I have done it like this, I'm getting minutes and seconds. I want hours too; how can I do this?

My code:

diff = data2-data1
divmod(diff.days * 86400 + diff.seconds, 60)
(3, 45)

How can I get hours too? Any help would be appreciated.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Mulagala
  • 8,231
  • 11
  • 29
  • 48
  • What have you tried? What is `c`? What are the two dates (if both `now`, how big a difference are you expecting?!) Have you read the [docs on `timedelta`](https://docs.python.org/2/library/datetime.html#timedelta-objects)? – jonrsharpe Jun 14 '14 at 07:40
  • @jonrsharpe, Sorry for my spell mistake i have corrected it – Mulagala Jun 14 '14 at 07:42
  • @tripleee, That is another way my requirement is differentiating with `datetime.datetime.now` – Mulagala Jun 14 '14 at 08:34

1 Answers1

66

Finally found solution

import datetime
data1 = datetime.datetime.now()
data2 = datetime.datetime.now()

diff = data2 - data1

days, seconds = diff.days, diff.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

print hours,minutes,seconds
swateek
  • 6,735
  • 8
  • 34
  • 48
Mulagala
  • 8,231
  • 11
  • 29
  • 48
  • 4
    `total_mins = (diff.days*1440 + diff.seconds/60)` to get the difference in minutes – Avishek Oct 27 '16 at 10:39
  • 22
    there is a `total_seconds()` defined so you can just use `hours = diff.total_seconds() / 3600` – justyy Oct 26 '18 at 13:37
  • 4
    ` total_seconds() ` overflows if time differance is over a few days. @Avishek solution is better because it does not overflow over a month. – Amir Samakar Apr 05 '20 at 01:41