SparkAndShine
SparkAndShine

Reputation: 18017

Python format timedelta greater than 24 hours for display only containing hours?

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?

Upvotes: 7

Views: 7573

Answers (3)

user7894079
user7894079

Reputation: 21

td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
result = '%d:%02d:%02d' % (seconds / 3600, seconds / 60 % 60, seconds % 60)

Upvotes: 2

Yuri G.
Yuri G.

Reputation: 4648

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'

Upvotes: 7

nagylzs
nagylzs

Reputation: 4180

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...)

Upvotes: 0

Related Questions