6

How do I format timedelta greater than 24 hours for display only containing hours in Python?

>>> import datetime
>>> td = datetime.timedelta(hours=36, minutes=10, seconds=10)
>>> str(td)
'1 day, 12:10:10'

# my expected result is:
'36:10:10'

I acheive it by:

import datetime

td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))

>>> print(str)
36:10:10

Is there a better way?

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
  • i think this is clean enough, why don't you use timestamp – Sinux Dec 07 '15 at 14:15
  • @Sinux because I do some calculations (`+, -`) over the time object. – SparkAndShine Dec 07 '15 at 14:25
  • related: [How to convert datetime.timedelta to minutes, hours in Python?](http://stackoverflow.com/q/14190045/4279) – jfs Dec 08 '15 at 20:24
  • If I wanted to remove the day from the following command: td = datetime.timedelta(hours= h,hours = m,hours = s) in order to get the following result 12:10:10 instead of: '1 day, 12:10:10' How would someone do it?! – Devilhorn Dec 21 '20 at 00:32

3 Answers3

6

May be defining your class that inherits datetime.timedelta will be a little more elegant

class mytimedelta(datetime.timedelta):
   def __str__(self):
      seconds = self.total_seconds()
         hours = seconds // 3600
         minutes = (seconds % 3600) // 60
         seconds = seconds % 60
         str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))
         return (str)

td = mytimedelta(hours=36, minutes=10, seconds=10)

>>> str(td)
prints '36:10:10'
Yuri G.
  • 4,323
  • 1
  • 17
  • 32
2
td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
result = '%d:%02d:%02d' % (seconds / 3600, seconds / 60 % 60, seconds % 60)
0
from datetime import timedelta
from babel.dates import format_timedelta
delta = timedelta(days=6)
format_timedelta(delta, locale='en_US')
u'1 week'

More info: http://babel.pocoo.org/docs/dates/

This will format your interval according to a given locale. I guess it is better, because it will always use the official format for your locale.

Oh, and it has a granularity parameter. (I hope I could understand your question...)

nagylzs
  • 3,954
  • 6
  • 39
  • 70