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

我是研究僧i 提交于 2019-11-26 17:20:03

问题


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?


回答1:


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'



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/34134971/python-format-timedelta-greater-than-24-hours-for-display-only-containing-hours

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!