31

How do I return or turn a timedelta, which is bigger than 24 hours, into an object containing the total hours and minutes (for example, 26:30) instead of "1 day, 2:30"?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ThomasD
  • 2,374
  • 6
  • 34
  • 51

3 Answers3

48

You can use total_seconds() to compute the number of seconds. This can then be turned into minutes or hours:

>>> datetime.timedelta(days=3).total_seconds()
259200.0
Simeon Visser
  • 113,587
  • 18
  • 171
  • 175
  • 4
    Right answer, but it would be helpful to add the simple `//60` and `%60` uses needed to turn it into an (hours, days) pair! – Alex Martelli Jan 13 '15 at 00:13
  • 1
    Thanks. I ended using the answer I found here: http://stackoverflow.com/questions/14190045/how-to-convert-datetime-timedelta-to-minutes-hours-in-python – ThomasD Jan 13 '15 at 15:47
23

Completing the answer of Visser using timedelta.total_seconds() :

import datetime
duration = datetime.timedelta(days = 2, hours = 4, minutes = 15)

Once we got a timedelta object:

totsec = duration.total_seconds()
h = totsec//3600
m = (totsec%3600) // 60
sec =(totsec%3600)%60 #just for reference
print "%d:%d" %(h,m)

Out: 52:15
G M
  • 17,694
  • 10
  • 75
  • 78
2
offset_seconds = timedelta.total_seconds()

if offset_seconds < 0:
    sign = "-"
else:
    sign = "+"

# we will prepend the sign while formatting
if offset_seconds < 0:
    offset_seconds *= -1

offset_hours = offset_seconds / 3600.0
offset_minutes = (offset_hours % 1) * 60

offset = "{:02d}:{:02d}".format(int(offset_hours), int(offset_minutes))
offset = sign + offset