Python timedelta format over 24 hours to display with clock only?

How do I configure timedelta for more than 24 hours to display containing only 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 get it:

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?

+1
source share
3 answers

Maybe defining your class that inherits datetime.timedeltawill 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'
+2
source
from datetime import timedelta
from babel.dates import format_timedelta
delta = timedelta(days=6)
format_timedelta(delta, locale='en_US')
u'1 week'

Additional information: http://babel.pocoo.org/docs/dates/

This will format your interval according to the given language. I think this is better because it will always use the official format for your locale.

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

0
source
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
source

Source: https://habr.com/ru/post/1694167/


All Articles