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

狂风中的少年 提交于 2019-11-28 01:34:39

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

td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
result = '%d:%02d:%02d' % (seconds / 3600, seconds / 60 % 60, seconds % 60)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!