<p>您需要将一个<code>timedelta</code>的内部数值转换为不同的时间单位,这些时间单位与它存储的时间单位不同,分别是<em><code>days</code></em>、<em><code>seconds</code></em>和<em><code>microseconds</code></em></p>
<p>既然您说自己无法将它们转换为字符串,那么一个潜在的解决方法可能是将它们转换为<code>timedelta</code>子类,该子类可以按照您想要的方式将自身转换为字符串</p>
<p>需要记住的一件事是<code>timedelta</code>可能包含巨大的值,必须以某种方式进行处理-因此,仅仅说您想要“MM:SS.sss”格式忽略了一个事实,即理论上也可能涉及数天和数小时。下面的函数计算它们,但仅在它们非零时显示它们的值</p>
<p>下面的代码定义了一个新的<code>MyTimeDelta</code>子类并使用它。我已经定义了子类“<code>__str__()</code>方法以返回所需格式的字符串。现在,每当新类的实例转换为字符串时,都会使用前一个函数,但该类作为一个整体仍然像它的基类一样是“数值的”。子类“<code>__str__()</code>方法使用了我添加的名为<code>_convert_units()</code>的私有助手方法</p>
<pre><code>from datetime import timedelta
class MyTimeDelta(timedelta):
@classmethod
def from_another(cls, other):
if not isinstance(other, timedelta):
raise TypeError('unsupported type')
return cls(days=other.days, seconds=other.seconds, microseconds=other.microseconds)
def __str__(self):
""" Format a timedelta into this format D:H:MM:SS.sss """
res = []
days, hours, minutes, seconds = self._convert_units()
if days:
res.append(f'{days}:')
if hours or days:
res.append(f'{hours}:')
if minutes or hours or days:
res.append(f'{minutes:02d}:')
res.append(f'{seconds}')
return ''.join(res)
def _convert_units(self):
""" Convert a timedelta to days, hours, minutes, & seconds."""
days = self.days
hours, remainder = divmod(self.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
seconds += self.microseconds / 1e6
return days, hours, minutes, seconds
times = ["1:23.921", "1:24.690", "1:24.790"]
def string_con(string_time):
""" Convert string_time to timedelta object. """
split_time = string_time.split(":")
split_secs = split_time[1].split(".")
mins, secs, ms = map(int, (split_time[0], split_secs[0], split_secs[1]))
return timedelta(minutes=mins, seconds=secs, milliseconds=ms)
def average_pace(laps):
""" Compute average pace using timedelta objects. """
laps = [string_con(lap) for lap in laps]
return sum(laps, timedelta(0)) / len(laps)
avg = MyTimeDelta.from_another(average_pace(times))
print(f'{avg.days=}, {avg.seconds=}, {avg.microseconds=}')
print(avg)
</code></pre>